Reputation: 263
I have a bunch of rows in a MySQL database table, with a last_update (TIMESTAMP) field to log when they were last modified. As of right now, I loop through all of the rows every 300 seconds and check to see if 3+ hours have elapsed, and then update that row if so.
$update_delay = 180;
$table_name = $wpdb->prefix . "products";
$results = $wpdb->get_results( "SELECT id, prod_id, last_update FROM $table_name" );
foreach ($results as $result)
{
$last_update = $result->last_update;
if (time() - strtotime($last_update) > $update_delay * 60)
{
As this is inefficient, I would like to query just the rows where the timestamp is older than 3 hours. Since that field has the format of "2020-03-01 23:22:06" I think I can do something like the following, but am not sure if I can do this using INTERVAL in the query, or if the date to check against should be in PHP.
$old_timestamp = date('Y-m-d G:i:s') . "- 3 hours";
$results = $wpdb->get_results( "SELECT id, prod_id FROM $table_name WHERE last_update > $old_timestamp" );
What would be a good option to implement this efficiently?
Upvotes: 0
Views: 993
Reputation: 3
Something like this?
$old_timestamp = date('Y-m-d G:i:s');
$results = $wpdb->get_results(
"SELECT id, prod_id FROM $table_name WHERE last_update > date_add($old_timestamp") -3 hours)
);
Upvotes: 0
Reputation: 222402
I would like to query just the rows where the timestamp is older than 3 hours
No need for specific application code. MySQL understands date arithmetics:
WHERE last_update > NOW() - INTERVAL 3 HOUR
Upvotes: 4