Jump to content

WHERE issues with date field


kyle.m

Recommended Posts

I have a table that has id and date columns.  For whatever reason, the following works:

 

$result = mysql_query("SELECT MAX(id) FROM table WHERE date > " . date("Y-m-d"));

$row = mysql_fetch_array($result);                                       

$num = $row['MAX(id)'];

 

However, the following does not:

 

$result = mysql_query("SELECT MAX(id) FROM table WHERE date < " . date("Y-m-d"));

$row = mysql_fetch_array($result);                                       

$num = $row['MAX(id)'];

 

Note that the only change is from using a greater-than operator to a less than operator.  I have three entries in the table with the values:

 

2011-01-17

2011-01-18

2011-01-19

 

And the date(...) call is returning "2011-01-18".  I can't figure out why one query would work while the other does not.  This is tested in both the php page and using the SQL tool in phpMyAdmin.  Any insight on this would be greatly appreciated.

Link to comment
Share on other sites

I figured it out, binding quotes around the date field worked.

 

$result = mysql_query("SELECT MAX(id) FROM table WHERE date > \"" . date("Y-m-d") . "\"");

 

Although I'm still not sure why this works with one operator and not the other.

Link to comment
Share on other sites

What happens if you use the MySQL CURDATE() function instead of concatenating in the php date() function?

 

SELECT MAX(id) FROM comics WHERE date > CURDATE()
SELECT MAX(id) FROM comics WHERE date < CURDATE()

 

That works as well (and seems to be a more elegant solution than my own).  Thank you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.