Monday, April 23

using PEAR Date with MySQL

So today, my small realization cost me some work, but simplicity in the result. I discovered that if you use the PEAR function Date(), you can correspond that directly to a MySQL database. Previously, I was using Date to format the date how I wanted it, but then using a UNIX timestamp to make sure the dates appeared in order. All I really needed to do was have the field type for the MySQL database be datetime. The output for Date() is the current date and time in the format YYYY-MM-DD HH:MM:SS, which is the MySQL format for datetime. I ran into this little problem. Before sticking a date into the database, you need to convert it into a string. I was trying to do:

$date = new Date();
and just inserting that... I'd get the error Catchable fatal error: Object of class Date could not be converted to string in...

What I really needed to do was:
$d = new Date();
$date = $d->getDate();
Which converts the output to a string before putting it into the database. It worked much better. So the next really cool thing I discovered is, once that's in the database, if you want to call out anything with a date after today (say for some sort of due dates or schedule) you can use the MySQL function date(). Such as:
//get all fields from table sched where date is after now
mysql_query("SELECT * FROM sched WHERE date>now()");
That saves a lot of trouble.

No comments: