Storing DateTime in MySql using PHP and performing subtraction to get difference in days and hours
I googled a bit but I cannot figure out how to use DateTime function and store in MySql using PHP. Also I need to subtract the stored date in the database from current date, and also stored time from current time开发者_开发百科. I don't wish to use separate date() and time() function. I wish to store both date and time in one column in MySql using PHP and get individual result of subtraction of date and time. How can I achieve this?
Try:
<?php
$insert_query = "INSERT INTO `table_name`(`date_time`) VALUES('".date('Y-n-j H:i:s', time())."')";
function timeDifference($timestamp, $type = 'd'){
$diff_seconds = $timestamp - time();
$diff_secs = $diff_seconds;
$diff_weeks = floor($diff_seconds/604800);
$diff_seconds -= $diff_weeks * 604800;
$diff_days = floor($diff_seconds/86400);
$diff_seconds -= $diff_days * 86400;
$diff_hours = floor($diff_seconds/3600);
$diff_seconds -= $diff_hours * 3600;
$diff_minutes = floor($diff_seconds/60);
$diff_seconds -= $diff_minutes * 60;
if($type === 's'){
return $diff_secs;
} elseif($type === 'm'){
return $diff_minutes;
} elseif($type === 'h'){
return $diff_hours;
} elseif($type === 'd'){
return $diff_days;
} elseif($type === 'w'){
return $diff_weeks;
}
}
$select_query = 'SELECT UNIX_TIMESTAMP(`date_time`) `date_time` FROM `table_name`';
$select_result = mysql_query($select_query);
if(is_resource($select_result) && mysql_num_rows($select_result) > 0){
while($row = mysql_fetch_assoc($select_result)){
echo 'Days difference is: '.timeDifference($row['date_time'], 'd').
', and hours difference is: '.timeDifference($row['date_time'], 'h');
}
} else{
echo 'No records found';
}
?>
精彩评论