Filtering a MySQL database with a date restriction
I have a MySQL table with a datetime field. I need to make a PHP script that will take all rows whose datetime field falls within that of a user-specified begin and end time. Anyone have a code snippet to do that?
Gil Hildebrand, Jr.
Internet Consultant
New Orleans, LA
Mark Hensler posted this at 05:59 — 21st January 2001.
He has: 4,048 posts
Joined: Aug 2000
simple...
in your query say:
"WHERE field_name >= date_time AND field_name <= date_time"
As for user defined, just replace "date_time" with $user_time (or whatever you call the var)
I recomend you use timestamps for ALL your date/time storage. You can then pull any date/time info out of it that you wish.
Mark Hensler
If there is no answer on Google, then there is no question.
Gil posted this at 06:05 — 21st January 2001.
They have: 103 posts
Joined: Apr 1999
Wow I didn't think it would be THAT easy. I figured you're have to do some PHP work for that. MySQL is a great thing...
Maverick posted this at 22:20 — 21st January 2001.
They have: 334 posts
Joined: Dec 1999
Actually, you are probably going to need to manipulate things a bit with PHP. That SQL query is fine, but don't forget that MySQL will store a datetime field as "2001-01-21 17:15:00" for 5:15 pm January 21st, 2001 (the time I'm writing this) and you need really really smart users to be able to enter their search queries in such a structured format. If they use a period instead of a colon, the query will fail. I'm assuming that you'll want to make things a bit easier on them, I.E., allow them to choose month, date, time ranges, etc, from a series of drop down lists or radio buttons. If that's the case, you'll need a little PHP to combine the various pieces of the search string into a something that MySQL can understand. For example, assume you use separate variables for year, month, day, hours, minutes and seconds, you'd need to combine them into a proper string like:
$searchstring="$year-$month-$day $hours:$minutes:$seconds";
then, you can use that $searchstring to query the database to assure that it's in a format that matches the datetime field.
Mark Hensler posted this at 22:45 — 21st January 2001.
He has: 4,048 posts
Joined: Aug 2000
the datetime thing came be avoided it you use the TIMESTAMP data type in the mySQL DB.
Simply provide the user with dropdowns or whatever (as Maverick suggested).
Then, use the mktime() function to create a timestamp to use in your queries.
To put info into the DB, use the time() function to insert a timestamp into your timestamp field.
Good Luck,
Mark Hensler
If there is no answer on Google, then there is no question.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.