TylerM
TylerM

Reputation: 151

PHP Comparing date in table with current date

I am trying to compare a stored date to the current date, and send back data accordingly. I'm not fluent in PHP so this is what I have so far

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $event_date_str = $row["date"];
    $todays_date_str = date("m-j-Y");

    $today = strtotime($todays_date_str); 
    $event_date = strtotime($event_date_str);
    if($event_date > $today){
    $event = array();
    $event["pid"] = $row["pid"];
    $event["name"] = $row["name"];
    $event["longitude"] = $row["longitude"];
    $event["latitude"] = $row["latitude"];
    $event["pavement"] = $row["pavement"];
    $event["traffic"] = $row["traffic"];
    $event["environment"] = $row["environment"];
    $event["image_b64"] = $row["image_b64"];
    $event["created_at"] = $row["created_at"];
    $event["date"] = $row["date"];
    $event["time"] = $row["time"];
    $event["type"] = $row["type"];
    // push single product into final response array
    array_push($response["events"], $event);
    }else{
    //delete it here
    }

With that code right there I am getting nothing back. I have 2 items stored in the database, One with the date "2-28-2014" and another with "2-14-2014", so I should be getting one back and not the other but I am getting neither back. I know that there are no leading zeros with the dates saved so I should use j right? Could someone help me figure out why this is not working, sorry if it seems like a simple question.

Thank you in advance,

Tyler

Upvotes: 0

Views: 306

Answers (1)

CodeAngry
CodeAngry

Reputation: 12985

This is not an efficient way to do things. If you need to pick items based on date, do it in the MySQL query directly. PHP filtering will always be slower than MySQL. Especially since you have to deliver extra data over network when filtering at PHP level.

So do it like this:

SELECT * FROM `table` WHERE `record_expires_datetime_gmt` > UTC_TIMESTAMP();
SELECT * FROM `table` WHERE `record_expires_date_gmt` > DATE(UTC_TIMESTAMP());
// use NOW() for local time, UTC_TIMESTAMP() is GMT/UTC

Then do what you need to do with the records. Never SELECT * and then filter records in PHP.

There's a whole set of DATETIME functions in MySQL to allow you MySQL server side filtering of data.

PS: Obviously, for this method to work, your MySQL table has to be properly designed. Date (date and time) fields need to be of type DATE or DATETIME not surrogate strings that are meaningful only within your project.

Upvotes: 2

Related Questions