0

Is it possible to use an if statement in a MySQL query in a similar what I'm showing? I want to grab some information for upcoming events(not ones with previous dates).

ini_set('date.timezone', 'America/New_York');
    echo $timestamp = date('Y-m-d'); 
    $sql = "select eventID,eventTitle,eventDate from events where eventLocationID = $locationID AND (eventDate > $timestamp) ORDER BY eventDate ASC";

edit - the sql statement isn't filtering out dates prior to today (it's displaying everything).

For example, I'm echoing the timestamp just to be sure it's setting properly. In my table I entered two dates, one in january and one today.

So here is the output

  2012-05-31 //timestamp, not part of results. just for reference
  2012-01-10 //first result, however it shouldn't display
  2012-06-22 //this should be the only result that displays
0

1 Answer 1

6

Just use a where clause:

$date = date('Y-m-d');
$sql = "
    SELECT 
        foo 
    FROM 
        bar 
    WHERE
        eventLocationId = ... 
        AND eventDate > '$date' 
    ORDER BY 
        eventDate DESC
";

Also, m/d/Y is not a valid date format for MySQL. It expects Y-m-d.


On a note not directly related to your question:

I really want to avoid doing post-query if statements

If you filter a resultset in PHP, it's going to many times slower than if you use a where clause. Databases are made to filter records quickly and efficiently. And, filtering in PHP requires you to actually transfer all of the results from MySQL to PHP (another slow down).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, wow that was painfully obvious now that I look at it. It's been a long day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.