Skip to content
Advertisement

Limit MYSQL search results to dates greater than variable

I have a MYSQL table posts which contains a VARCHAR(25) column created that is filled with datetimes in the format XXXX-XX XX:XX:XX. I’m attempting to search by dates > now – 24 hours.

//get the timestamp for now - 24 hours
$timeAgo=date("Y-m-d H:i:s", strtotime('-24 hours'));
//outputs something like 2020-09-17 12:32:44

//search for all posts that meet the criteria
$sql = "SELECT posts.*
        FROM posts
        WHERE posts.uuid='uuid1' 
        OR posts.uuid='uuid2' 
        OR posts.uuid='uuid3'
        AND posts.created > '$timeAgo'
        ORDER BY posts.id DESC
        ";

When searching with just one posts.uuid I get the desired result, which lists all posts from that uuid that are within the last 24 hours (or other specified time).

When I search with multiple uuids as referenced in the code block above, I get undesired results which lists all posts from the respective uuids, regardless of when they were created.

How can I search for all posts within the last 24 hours (or other specified time) with multiple posts.uuids?

Advertisement

Answer

You need parentheses around the OR conditions:

WHERE 
    (posts.uuid='uuid1' OR posts.uuid='uuid2' OR posts.uuid='uuid3')
    AND posts.created > '$timeAgo'

Rationale: AND has higher prescedence than OR, so without parentheses the expression is equivalent to:

WHERE 
    posts.uuid='uuid1' 
    OR posts.uuid='uuid2' 
    OR (posts.uuid='uuid3' AND posts.created > '$timeAgo')

It is simpler to use IN:

WHERE posts.uuid in ('uuid1', 'uuid2', 'uuid3') AND posts.created > '$timeAgo'

Note that you can compute the date directly in the query rather than in PHP. Also, you don’t need to prefix the columns with the table name, since only one table is involved in the query. I would phrae this as:

SELECT *
FROM posts
WHERE uuid IN ('uuid1', 'uuid2', 'uuid3') AND created > now() - interval 1 day
ORDER BY id DESC
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement