Category Archives: php

date difference or count day or month or year between two dates in php

If you have a get a date difference between two dates like 2 days left or 1 month left count from current date to start date than it code is useful for you..

<?php

$date2 = date(“d-m-Y H:i:s”,strtotime($row[‘end_date_time’]));
// where $row[‘end_date_time’] is your start data
$date1 = date(“d-m-Y H:i:s”,strtotime(date(‘Y-m-d H:i:s’)));

$diff = abs(strtotime($date2) – strtotime($date1));

$years   = floor($diff / (365*60*60*24));
$months  = floor(($diff –
$years * 365*60*60*24) / (30*60*60*24));
$days    = floor(($diff –
$years * 365*60*60*24 – $months*30*60*60*24)/ (60*60*24));
$hours   =
floor(($diff – $years * 365*60*60*24 – $months*30*60*60*24 –
$days*60*60*24)/ (60*60));
$minuts  = floor(($diff – $years *
365*60*60*24 – $months*30*60*60*24 – $days*60*60*24 – $hours*60*60)/
60);  $seconds = floor(($diff – $years * 365*60*60*24 –
$months*30*60*60*24 – $days*60*60*24 – $hours*60*60 – $minuts*60));

printf(“%d years, %d months, %d days, %d hours, %d minuts\n, %d
seconds\n”, $years, $months, $days, $hours, $minuts, $seconds);

?>

google map with calculate between more than two places in php

<?php
$travel_location = ‘1st main Road&Peenya Industrial Area’;

$bootloca = explode(‘&’,$travel_location);
$origins = str_replace(‘ ‘, ‘+’, $_REQUEST[‘city’]);
$destinations = ”;
foreach($bootloca as $book):
$destinations = $destinations.str_replace(‘ ‘, ‘+’, $book).’|’;

endforeach;

$json=file_get_contents(“http://maps.googleapis.com/maps/api/distancematrix/json?origins=&#8221;.$origins.”&destinations=”.$destinations.”&mode=driving&sensor=false”);

$json=json_decode($json,true);
//print ‘<pre>’;
//print_r($json);   // for check array value
//print ‘</pre>’;
$total_distance = 0;
foreach($json[“rows”][0][“elements”] as $dist):

$total_distance += ceil($dist[“distance”][“text”]);

endforeach;

print $total_distance;
?>

column and row wise total calculation with array in php or joomla custom component with jQuery

IN Html section

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&#8221; type=”text/javascript” charset=”utf-8″></script>
<script>

$(document).ready(function() {

$(“input”).click(function(event) {

var id = $(this).closest(‘td’).attr(‘id’);
// alert(id);
var menuid = id.replace(“menu_”,””);
updateTotal(menuid);
});

//    multiplyer
$(“input[name=’multiplyer[]’]”).blur(function(event) {
var value = $(this).val();
//alert(value);
var textid = $(this).attr(‘id’);
var multiplyerid = textid.replace(“multiplyer_”,””);
var parentpriece =  $(‘#parentprice_’+multiplyerid).val();
var ttto = parentpriece*value;
var id = $(this).closest(‘td’).attr(‘id’);
// alert(id);
var menuid = id.replace(“menu_”,””);
//$(‘#totalprice’+menuid).val(ttto.toFixed(2));
$(‘#docfile’+multiplyerid).val(multiplyerid+’_’+ttto+’_’+value);
$(“#”+textid).click();
});

$(“input[name=’multiplyer[]’]”).click(function(event) {
var value = $(this).val();
//alert(value);
var textid = $(this).attr(‘id’);
var multiplyerid = textid.replace(“multiplyer_”,””);
var parentpriece =  $(‘#parentprice_’+multiplyerid).val();
var ttto = parentpriece*value;
var id = $(this).closest(‘td’).attr(‘id’);
// alert(id);
var menuid = id.replace(“menu_”,””);
//$(‘#totalprice’+menuid).val(ttto.toFixed(2));
$(‘#docfile’+multiplyerid).val(multiplyerid+’_’+ttto+’_’+value);
$(‘#multi_’+multiplyerid).text(ttto);
//select_price(multiplyerid,value);
$(“#”+textid).focus();
});

});

function updateTotal(id) {
//alert(id);
var total = 0;
var url = ”;
var multi = ”;
var nnn= 0;
$(“#menu_”+id+” input:checked”).each(function() {
var mainval = this.value;
var priceval = mainval.split(“_”);;
//alert(priceval[2]*priceval[1]);
//alert(priceval[1]);
total += parseFloat(priceval[1]);
url = url + ‘&’ + priceval[0];
multi = multi + ‘&’ + priceval[2];
// var mtot = parseFloat(priceval[1] * priceval[2]);
//alert(mtot);
//nnn = nnn + ‘&’ +( priceval[2]*priceval[1]);
});

//url string
$(‘#docdetailid’+id).val(url);
//total
$(‘#totalprice’+id).val(total.toFixed(2));
// multiplyer
$(‘#docmultiprice’+id).val(multi);
//indivisual total
//$(‘#indprice’+id).val(nnn.toFixed(2));
}

$(document).ready(function () {
$(‘#myLink’).click(function () {
$(“input[id^=’priceid’]”).attr(‘checked’, $(‘#myLink’).is(‘:checked’));
});
});

$(document).ready(function () {
$(‘#sendinvoice’).click(function () {
if (!$(‘input[name=”priceid[]”]’).is(‘:checked’)) {
$(“#invoiceerror”).fadeIn().text(“You must check at least one option.”);
return false;
}

});

});

</script>

<form name=”docf” id=”docf” method=”post” action=”<?php echo JRoute::_(‘index.php?option=com_support&task=file.savaprice’); ?>”>

<table width=”100%” border=”1″ cellspacing=”2″ cellpadding=”2″>

<tr>

<td><input type=”checkbox” id=”myLink”  /></td>

<td><strong>Tax File No </strong></td>

<td>files</td>

<td>Price</td>

</tr>

<?php foreach ($this->items as $i => $item) :?>

<tr>

<td><input type=”checkbox” name=”priceid[]” value=”<?php print $item->id?>” id=”priceid” /></td>

<td><a href=”<?php echo JRoute::_(‘index.php?option=com_support&view=file&id=’ . (int)$item->id); ?>”><b><?php echo $item->wintaxno; ?></b></a>

<input type=”hidden”  value=”<?php echo $item->wintaxno; ?>” name=”wintaxno[]”   />

<input type=”hidden”  value=”<?php echo $taxyear; ?>” name=”taxyear[]”   />

</td>

<td id=”menu_<?php print $item->id?>”>

<?php

$db =& JFactory::getDBO();

$sql = “SELECT * FROM #__support_docdetail where parent_id=0 order by id,parent_id asc”;

//print $sql;

$db->setQuery($sql);

$db->query();

$docdetail = $db->loadObjectList();

foreach($docdetail as $doc):

if($doc->is_parent==”N”):

?>

<input name=”docfile[]” type=”checkbox” value=”<?php print $doc->id ?>_<?php print $doc->price ?>_1″ />

<?php print $doc->doclabel ?>&nbsp;&nbsp;$(<?php print $doc->price ?>)<br />

<?php else:?>

<input name=”docfile[]” type=”checkbox” disabled=”disabled” checked=”checked” value=”<?php print $doc->id ?>_<?php print $doc->price ?>_1″ />

<?php print $doc->doclabel ?><br />

<?php

$db =& JFactory::getDBO();

$sql = “SELECT * FROM #__support_docdetail where parent_id=”.$doc->id;

//print $sql;

$db->setQuery($sql);

$db->query();

$docdetailparent = $db->loadObjectList();

foreach($docdetailparent as $docparent):

?>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name=”docfile[]” type=”checkbox” value=”<?php print $docparent->id ?>_<?php print $docparent->price ?>_0″ id=”docfile<?php print $docparent->id ?>” />

<?php print $docparent->doclabel ?>&nbsp;&nbsp;$(<?php print $docparent->price ?>)&nbsp;&nbsp;x&nbsp;&nbsp;

<input type=”hidden” name=”parent_price[]” id=”parentprice_<?php print $docparent->id ?>” value=”<?php print $docparent->price ?>” />

<input type=”text” name=”multiplyer[]” id=”multiplyer_<?php print $docparent->id ?>” size=”5″ value=”1″ style=”width:30px; text-align:right” /> = <span id=”multi_<?php print $docparent->id ?>”><?php print $docparent->price ?></span><br />

<?php  endforeach; ?>

<?php endif; ?>

<?php endforeach; ?>

<input type=”hidden”  value=”” name=”docdetailid[]” id=”docdetailid<?php print $item->id?>”  />

<input type=”hidden”  value=”” name=”docmultiprice[]” id=”docmultiprice<?php print $item->id?>”  />

<input type=”text”  value=”” name=”indprice[]” id=”indprice<?php print $item->id?>”  />

</td>

<td><input type=”text” readonly=”readonly” value=”” name=”totalprice[]” id=”totalprice<?php print $item->id?>” size=”10″ style=”width:50px;” /></td>

</tr>

<?php endforeach; ?>

<tr><td colspan=”4″ align=”right”><input type=”submit” id=”sendinvoice” value=”Send Invoice” name=”submit” /></td></tr>

</table>

<input type=”hidden” name=”option” value=”com_support” />

<input type=”hidden” name=”task” value=”file.savaprice” />

<?php echo JHtml::_(‘form.token’); ?>

</form>

IN php with save record

public function savaprice()

{
JSession::checkToken() or jexit(JText::_(‘JINVALID_TOKEN’));
//print_r($_REQUEST);

foreach ($_POST[‘doc_id’] as $row=>$id)
{
$id = $id;
$totalprice = $_POST[‘totalprice’][$row];
$multiplyer = $_POST[‘multiplyer’][$row];

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert(‘#__support_docprice’);
$query->set(“file_id='”.$id.”‘, docfile='”.$docfile.”‘,price='”.$totalprice.”‘,multiplyer='”.$multiplyer.”‘,wintaxno='”.$_REQUEST[‘wintaxno’].”‘,taxyear='”.$_REQUEST[‘taxyear’].”‘,federalposition='”.$_REQUEST[‘federalposition’].”‘,stateposition='”.$_REQUEST[‘stateposition’].”‘,taxtotal='”.$_REQUEST[‘taxtotal’].”‘,sut='”.$_REQUEST[‘sut’].”‘,pt='”.$_REQUEST[‘pt’].”‘,mat='”.$_REQUEST[‘mat’].”‘,withfederalposition='”.$_REQUEST[‘withfederalposition’].”‘,withstateposition='”.$_REQUEST[‘withstateposition’].”‘,cityposition='”.$_REQUEST[‘cityposition’].”‘,withcityposition='”.$_REQUEST[‘withcityposition’].”‘ “);
//print $query;
$db->setQuery($query);
$db->query();
}$this->setMessage(JText::_(‘Item saved successfully’));

$this->setRedirect(JRoute::_(‘index.php?com_support&view=files&layout=userlist’, false));

}

 

array value insert table in php with mysql

<form name=’frm’ method=”post” action=’#’>

<input type=”text” name=”id[]” value=””  />

<input type=”text” name=”name[]” value=””  />

<input type=”submit” id=”submit” value=”submit” name=”submit” />

</from>

in php code

foreach ($_POST[‘id’] as $row=>$id)
{

$id = $id;

$name = $_POST[‘name’][$row];

print ‘insert into table name value(‘.$id.’,”‘.$name.'”)’;

}

Get last record using php or php with mysql

For example: In this example explode commas and make a linkable every word.

<?php
$ash = ‘1,2,3,4’;
$ashval = explode(‘,’,$ash);

foreach($ashval as $val)
{
print “<a href=”>”.$val.”</a>”;
if($val!=end($ashval))
{
print ‘,’;
}
else
{
print ”;
}

}
?>

OR you can use another method:

<?php
$ash = ‘1,2,3,4’;
$ashval = explode(‘,’,$ash);
$checkval=count($ashval);

foreach($ashval as $val)
{

if($checkval!=$val)
{
$te=”,”;
}
else
{
$te=””;
}
print “<a href=”>”. $val.”</a>”.$te;

}
?>

ATM Machine logic in PHP.

Q. Consider a hypothetical ATM machine which gives you notes of 10, 20, 50, 100, 500 & 1000 in denomination. If I enter 5,550 Rs. It should give me 5 notes of 1000, 1 note of 500 and 1 note of 50. ATM machines cannot store coins. So, if input amount is something like 1978 then machine should print “Invalid Amount”.

A .

<?php

$amount=$_REQUEST[‘amount’];
$rupees = array(1000,500,100,50,20,10);
$count = array(0,0,0,0,0);

for($i=0;$i<count($rupees);$i++):
if($rupees[$i]<$amount || $rupees[$i]==$amount):
$count[$i]=floor($amount/$rupees[$i]);
$amount=$amount%$rupees[$i];
endif;
endfor;
print ‘<b>Input=</b>’.$_REQUEST[‘amount’].'<br>’;

if($amount==0):
for($i=0;$i<count($count);$i++):

if($count[$i]!=0):

echo ($rupees[$i].’ * ‘.+$count[$i] .’=’. ($rupees[$i]*$count[$i])).'<br>’;
$tot += $rupees[$i]*$count[$i];
endif;
endfor;
print ‘<b>Total=</b>’.$tot;
else:
print ‘<b>Invalid Amount ‘.$_REQUEST[‘amount’].'</b>’;
endif;

?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>AIM MACHINE</title>
</head>

<body>
<form name=”frm” method=”post” action=”#”>
Enter value:<input type=”text” name=”amount” value=”” />
<input type=”submit” name=”submit” value=”submit” />
</form>
</body>
</html>

Display Indian current time in PHP

This small snippet explains how to get Indian Time in PHP without changing the server times and timezones. So irrespective of whether your server is in PST or GMT, you can still display IST when displaying this with PHP.

<?php
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
echo  $date->format( 'H:i:s A  /  D, M jS, Y' );
?>

Here is a list of supported timezones in PHP for your reference.

for loops to create a multiplication table for php

<?php
$start = 1;
$end = 10;

print ‘<table border=”1″ cellspacing=”0″ cellpadding=”5″>’;
for ($y = $start – 1; $y <= $end; ++$y) {
print “<tr>”;
for ($x = $start – 1; $x <= $end; ++$x) {
if ($y == $start – 1) {
print “<td><b>$x</b></td>”;

} else if ($x == $start – 1) {
print “<td><b>$y</b></td>”;
} else {
print “<td>”;
print $x*$y;
print “</td>”;
}
}
print “</tr>”;
}
print “</table>”;?>

joomla store value Using the JTable Class

The first step is to extend the JTable class with your new table class in table folder:

class TableRestaurant extends JTable 
   { 
   var $id = null; 
   var $name = null; 
   var $address = null; 
   var $comments = null; 
   var $comment_date = null;
   var $published = null; 
   function __construct(&$db) 
      {
      parent::__construct( '#__restaurant', 'id', $db );
      } 
   }

To include the file, place this line in your extension's source code (use com_nameofyourcomponent in place of com_restaurant):
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_restaurant'.DS.'tables');
To get an instance of the object, use this code:
$row =& JTable::getInstance('restaurant', 'Table');

In a model class (extends JModel) you can also use:

$row =& $this->getTable('restaurant');

Updating is as simple as setting the row values in this manner.

$row->name = 'ashwin';
$row->address = 'test address';
$row->comments = 'Open Source Developer';
// Save results
$row->store();

Notice that the $row object of type TableRestaurant has all the columns we defined above.  When we call the store() method these rows are automatically stored in the database.  Our code above assumes that the id field will be auto-incremented on store(), so we are not providing a value for this field (as well as comment_date and published).  So this code will store a new value for this restaurant (essentially running and 'INSERT' query for us).  If we had provided value for the id field, the store() method would have instead 'UPDATE' query.

random coupon generator in php

<?php
	$passes = array();
 	$chars = "abcdefghkmnopqrstuvwxyz023456789";
	srand((double)microtime()*1000000);
	$amount = 100;
	$lenght = 6;   

	for($j=0; $j<$amount; $j++)
	{

		 $i = 0; $pass = '' ;
		 while ($i <= $length)
		 { $num = rand() % 33; $tmp = substr($chars, $num, 1);
		 $pass = $pass . $tmp; $i++;
		 }
		 $passes[] = $pass;
        }

	foreach($passes as $password)
	{
		echo strtoupper(substr(md5($password),0,15))."<br />";
	} 

?>