Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking MySQL's DATETIME in PHP

I lack some experience with PHP/MySQL environment. I have a MySQL table called MyTable. In it I have a field called RowTime of type DATETIME NOT NULL. After selecting the row in PHP, I want to check whether RowTime is older or younger than 3 days.

Given all the different types of time types, can someone please help completing the following code (I'm deliberately omitting various error handling):

$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];

// NEED HELP HERE to check whether $rowTime is older or younger than 3 days

mysqli_free_result($result);
like image 451
Free Bud Avatar asked Mar 21 '23 01:03

Free Bud


2 Answers

You can use special SQL operator to check that your date older than 3 days:

$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime, IF(RowTime + INTERVAL 3 DAYS > now(), true, false) as isYounger FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
if($myRow['isYounger']) {
    //record is younger
} else {
    //record is older
}
mysqli_free_result($result);
like image 170
Barif Avatar answered Mar 22 '23 16:03

Barif


You can use the following query:

SELECT RowTime,TIMEDIFF(NOW(),RowTime)>"72:00:00" AS "Old" FROM MyTable ;

This will introduce column "Old" which will be 1 if RowTime is older than 3 days. Otherwise it'll be 0. Please note that this doesn't take the timezone into account.

like image 32
vhu Avatar answered Mar 22 '23 15:03

vhu