views:

120

answers:

4

I want to allow my users to search the database for a row that was submitted on a certain day. The date is entered into the field in the database using the date() function which is great, but when i use the php strtotime function, of course the dates are not exactly the same.

Is there some clever mysql function that can help me with this?

A: 

Why not convert the timestamp generated by strtotime() into a MySQL formatted date? That way you're comparing apples to apples.

$mysql_formatted_date = date("Y-m-d", $timestamp);

Edit: If the timestamp is in the database use MySQL's date_format() to accomplish the same thing:

...    
WHERE DATE_FORMAT("y-m-d", timestamp_field) = $date_format
John Conde
the date in the database is a timstamp...
tarnfeld
response edited to reflect this information
John Conde
+1  A: 

I had an issue with this before.

You're best to generate a start and end date then use the BETWEEN function instead.

So something like this:

$start_date = "2009-01-01 00:00:00";
$end_date = "2009-01-01 23:59:59";

$sql = "SELECT * FROM table WHERE date BETWEEN '$start_date' AND '$end_date' AND id = 'x';

Of course you would just pull your dates from the DB using strtotime and append the time stamps - depends how you used date()

Hope this helps :)

foxed
Are events that happen precisely at midnight not important to you? (There's a one second gap in your clause.) :-)
middaparka
Quite right, oops ;)
foxed
haha and well i used this, but i did $searchedTime-86400 for the start and then +86400 for the end, so it searches within a day back and forward of the timestamp generated.... its accurate enough to give good results, but can sometimes be a bit vague
tarnfeld
A: 

PHP:

$timestamp_from_php = strtotime('December 25, 2009');

SQL:

select
    `fields`
from
    Table t
where
    date_format('Y-m-d', t.`datetime_field`) = date_format('Y-m-d', '$timestamp_from_php')
Björn
+1  A: 

You can use MySQL's DATE() function to extract date part of the timestamp:

select ... from table ... where DATE(date_column) = '2010-01-25';

If you have problem submitting '2010-01-25' from PHP, you can use PHP's date function with 'Y-m-d' as parameter to only get the date part.

$d = date('Y-m-d', strtotime(...));

Looking at your question closely, it seems you'll need both of those. First use PHP's date function to get only the date part and then use MySQL's date to match only those records.

Milan Babuškov