Adding time to time saved in mysql through PHP - php

I'm a very rookie programmer when it comes to PHP. I can usually manage most problems that I run into, but with this one I'm stumped.
I'm trying to create a program where a user can insert a name into a table, and 30 minutes after insertion the name would be flagged as "expired". I'm able to create the row in MySql and using MySql I can put the time when the name was entered. Now what I'm trying to do is take that time from the database and check if it's been 30 minutes since it was entered.
I figure I could do this by taking the time from the database, adding 30 minutes to it, then checking against the current time to see if its past it yet.
This is what I have so far. The time is in this format: 2013-08-21 13:18:35
$result = mysqli_query($con,"SELECT * FROM list ORDER BY id desc");
//snip snip
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['reason'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
cho "</tr>";
}
Now I know that I need to take $row['date'] and add 30 minutes to it. I've read probably about 20 different pages about this, but nothing I do seems to work.
I've seen a few different things suggest such as date_add() and strtotime but either I'm doing something wrong, or it doesn't work.
If I could just get a working code sample for how to add 30 minutes to $row['date'], I'm sure I could explain it to myself.
I know how to compare the two once I've got the 30 minutes added, and I think this would be correct:
if ($time30 < $now) {
// Code to execute
}
Any help would be appreciated.

Considering that $row['date'] prints out 2013-08-21 13:18:35. you need to use strtotime() to convert that value into a timestamp.
See documentation here strtotime.
Now that you have a timestamp, you simply add 1800 seconds to it (half an hour) and you obtain what you need.
Then, a simple comparison between your time and now (you obtain the value with time() ) will give you the result.
This code is a mere example (even too much detailed, because it can be shorter):
$db_time = strtotime("2013-08-21 20:18:35");
$half_hour = 1800;
$time = $db_time + $half_hour;
if($time < time()) echo "expired"; else echo "active";

First, avoid select *
Mysql solution would be to return the time after 30 mins as a column
SELECT TIMESTAMPADD(MINUTE,30,date1);
Assuming date1 is your column name avoid using date as a column name, at best its a maintenance issue

In PHP:
$time30 = strtotime($row['date']) + (30 * 60);
$now = time();
In MySQL
SELECT *,timestampadd(minute,30,date)<now() as expired FROM list ORDER BY id DESC
Then in the PHP you have $row['expired'] as a 1 or 0.

Related

Can't write the right if statement regarding time

I have a database with rows of employee information. In the data I have training dates that expire. I need to compare the expiration date that is pulled to the current date. I'd like to bold and turn red the date if it is within 30 days of expiring. So anytime the page is loaded if it is within that 30 day time frame it will stand out.
This is what I have currently without the if statement I am looking for:
$lic_ex = date("m/d/Y", strtotime($row['lic_ex']));
echo "<td>" . $lic_ex . "</td>";
Convert expiration date in DateTime object.
Create DateTime object which represents today date + 30 days.
$thirtyDaysLater = (new \DateTime('today'))->modify('+30 day');
Compare both objects and if DateTime object from 2. is bigger, then the person is in 30 days expiration period and you can bold the text
For example:
$expirationDate= DateTime::createFromFormat('m/d/y' , $input);
$compareDate = (new \DateTime('today'))->modify('+30 day');
if ($compareDate >= $expirationDate) {
echo "<td><strong>" . $lic_ex . "<\strong></td>";
} else {
echo "<td>" . $lic_ex . "</td>";
}
just adjust the createFromFormat parameters to your data

strtotime 1 month or older issue

I'm trying to evaluate and change the color of each row based on the age of the record. For some reason this statement evaluates incorrectly and just paints all rows grey. I have the following values stored in a varchar column
2015-01-12
2015-05-12
2015-05-12
So in theory the first one should be white background and the other two should be grey background. Where am I going wrong? Thanks!
while ($row = mysql_fetch_array($result))
{
$mydate = $row['Received_date'];
if($mydate < strtotime('1 month ago'))
{
echo "<tr bgcolor=\"#808080\">";
}
else
{
echo "<tr>";
}
echo "
<td style='font-size:12px;'><center>{$row['ID']}</center></td>
You are comparing a date value with a unix time value, and that doesn't work. You're halfway there, though! You're already calling strtotime() once; just do it twice and you should hopefully be fine.
$mydate = strtotime($row['Received_date']);

How to display number of minutes between two time fields in MySQL?

I'm working on a time management system and am currently stuck. I'm trying to use PHP to calculate the number of hours/minutes between two columns (from and to). These are both set as 'time' type so MySQL recognises it as a time datatype.
I've tried the following in PHP:
$from= isset($_GET['from']) ? '%'.$_GET['from'].'%' : '';
$to = isset($_GET['to']) ? '%'.$_GET['to'].'%' : '';
$diff = $to - $from;
echo "<table border='1'>
echo "<tr>";
echo "<td>" . $row[$diff] . "</td>";
echo "</tr>";
echo "</table>";
Say for example 'to' is set at 15:00:00 and from is set at 09:00:00, then the time difference for that row should be 6 hours and this should be displayed for that row.
The variable $difference is supposed to echo the difference in hours/minutes but it just displays the id assigned to that row instead. I'm trying to echo the number of minutes for each row in the table not just one.
I've seen the timediff function but don't know if that will do the trick.
I don't see your logic with the % and the $_GET vars, and $row suddenly appears out of nowhere.
You should convert the inputted times to php DateTime classes.
An example shows calculating diffs: http://nl1.php.net/manual/en/class.datetime.php#108970
Create your DateTime for example like this:
$dateFrom = new DateTime("2014-02-24 ".$_GET['from']);
$dateTo = new DateTime("2014-02-24 ".$_GET['to']);
$diff = $dateFrom->diff($dateTo);
print_r($diff) ;
The day you use is not really important if you only need the difference in time.

Date comparison working as long as time is 00:00:00

this is my events script that pulls out appointments for the next 7 days, it appears to work ok, but only under one condition........The dates and times are held in the mysql db in datetime format so 2013-12-23 08:30:00 . My script prints out each day and finds appointments for that day for customers that are dropping off or picking up things. The mysql looks through the db and matches the customers with the dropping off or picking up fields to the date being printed and adds them in the div below the date.
The problem I am having is that if the time is set to anything other than 00:00:00 it doesn't pickup that customer for that day. How do I get the comparison to ignore the time and only use the date ?.
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//
What you are doing right now is comparing date/time values to just date values. This comparison would fail if the time part is anything other than midnight.
You can fix the comparison by using the DATE() MySql function to compare apples with apples:
WHERE DATE(datedroppingoff) = '$theday' OR DATE(datepickingup) = '$theday'
There are other ways to do the same, for example
WHERE DATEDIFF(datedroppingoff, '$theday') = 0 OR ...
If you had a $nextday value at hand you could also do
WHERE (datedroppingoff >= '$theday' AND datedroppingoff < '$nextday') OR ...
You are storing a specific time and day in mySQL, but only search for a date in your SQL query. As mySQL does not understand the difference between you wanting to search for a complete day or a specific point in time, mySQL assumes you are looking for the day at time 0:00:00.
You have a few options, you could search for a time period (pseudo code, check the borders yourself):
WHERE datedroppingoff > '$theday' AND datedroppingoff < '$theday'+1
another option is to store the date and time in separate db fields. That way you can keep your SQL queries simpler.
Good luck.

if statements in php using dates

I want to write an IF statement based on two dates.
I have a MySQL database (of which I have no control over) for tests and exams taken.
One of the fields is labelled ClientTime and outputs the date and time the test was taken. When queried the typical output would read as such Thu Aug 25 16:47:05 GMT+0100 2011
The following all happens in a while loop
I’ve managed to convert this MySQL date using strtotime() to a d/m/Y format so the above would read 25/08/2011 and I can display a table with all the correct dates.
I also have a php form that asks for the number of days that this test will expire after and this gets stored in a variable $IMonths (from the $_POST['IMonths'] passed from the form page) - the php code will be changed to Months once I have it working but I am using days for the purpose of testing – hence the variable passed being called $IMonths.
I have also created a $today = date("d/m/Y"); variable
I can successfully create a new date using the following command $Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days")); and can display all results with both the test date and the expiry date.
I then want to include an if-statement within my while-statement that says is ($Expiry>$today) but it’s not accurate – there are no errors and changing the number of days changes the results.
My test database has 5 exams in with the following dates.
Taken 17/08/2011
Taken 17/08/2011
Taken 22/08/2011
Taken 22/08/2011
Taken 24/08/2011
If I set the expiry days to 1, I get all results back as expected:
If I set it to 10 days I get two results
Taken 17/08/2011
Taken 17/08/2011
I don’t get any of the others even though their date will be less than today's date (07/09/2011 (as I write this)) but they do expire in the month of September.
If I set the expiry days to 15, I get one result that is one day in the future!
Taken 17/08/2011
I hope that makes sense. My code is as follows:
<?php
// Make The MySQL Server Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
// Make The MySQL Database Connection
mysql_select_db("questions") or die(mysql_error());
$IQuizName = $_POST['IQuizName'];
$IMonths = $_POST['IMonths'];
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName='$IQuizName'
AND PassFail='Pass'") or die (mysql_error());
$today = date("d/m/Y");
echo "<table border='1'>";
echo "<tr> <th align='left'>Candidate Name </th> <th align='left'>Pass / Fail</th> <th align='left'>Date last Taken</th> <th align='left'>Expires</th> <th align='left'>Today</th> </tr>";
while($row = mysql_fetch_array($result)){
//START of expiry calculation
$Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days"));
if($Expiry>$today){
echo "<tr><td>";
echo $row['Candidate'];
echo "</td><td>";
echo $row['PassFail'];
echo "</td><td>";
//Date Conversion
echo date('d/m/Y', strtotime($row['ClientTime']));
echo "</td><td>";
echo $Expiry;
echo "</td><td>";
echo $today;
echo "</td><tr>";
};
}
echo "</table>";
echo "<P>";
?>
Your issue is due to datatypes in PHP. When you call the date() function in PHP, you are actually formatting dates into strings. So when you do $Expiry = date(blahblah), $expiry is now a string. So your if statement is if (somestring > someotherstring). Normally you would not think to compare one block of text to see if it is greater than another block of text.
http://www.php.net/manual/en/function.date.php
One way to get around this would be the strtotime function. This returns integers that are based on UNIX timestamp for the date representation.
http://www.php.net/manual/en/function.strtotime.php
If you convert your string dates to strtotime, your if statement is now comparing if one number is greater than another. This should solve your problem :)
First: fix that SQL-injection hole.
I suggest querying the expiry dates in SQL, it will be much easier.
Here's example code
//escape those user variables !!
$IQuizName = mysql_real_escape_string($_POST['IQuizName']);
$IMonths = mysql_real_escape_string($_POST['IMonths']);
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName= '$IQuizName'
AND PassFail= 'Pass'
AND ClientTime < NOW() ");
//don't use (or die(error)) in production code, (for now I'll let it slide).
if (!$result) then { die (mysql_error()); }
while ($row = mysql_fetch_row($result))
{
echo "the table"
}
For accurate comparing dates you should convert the dates with the strtotime function again.
In PHP there is no standard date data type. What you have is strings, and when you compare them, they get compared as strings, not as dates, thats why you get results you dont expect. How it normally is done in PHP is to format your date string by ordering from most significant bit to least bit, like
YYYY-MM-DD HH:MM:SS
If you do that, string comparison will work as expected. You can format your dates easily using:
$string = date('Y-m-d H:i:s', $year, $month, $day, $hour, $minute, $second);

Categories