简体   繁体   中英

Date comparison with PHP and Mysql

I have a table with a date field type date .

What I am trying to do is to do a comparison between the date from inside the table and the today date. If the date from the table is yesterday then insert the today date.

The thing I'm not sure about is how to insert the data in the database so I can make the comparison. here is what im thinking to do"

$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
    $oldTime = $y['date']; 
}

if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}

So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point.

Any ideas?

Thanks

You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT.

Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way:

date('Y-m-d', time())

or even better, to get the current date, you can use just this line:

date('Y-m-d')

To conclude, you can do the if in this way:

if( strtotime($oldTime) < strtotime(date('Y-m-d')) )

or even better:

if( strtotime($oldTime) < strtotime('now') )

To compare dates you can use strtotime($date); Where date can be a time(), mysql date or date('Ym-d'); string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM