Page 1 of 1
php/mysql question
Posted: Fri Oct 20, 2006 4:13 pm
by garry27
how do i convert a date from php to mysql and then back again?
at the moment i have the following code:
Code: Select all
$day = int ( stripslashes ( trim ( $_POST['day'] ) ) );
$month = int ( stripslashes (trim ( $_POST['month'] ) ) );
$year = int ( stripslashes ( trim ( $_POST['year'] ) ) );
and i need to get it into mysql 0000-00-00 format
thanks
Posted: Fri Oct 20, 2006 4:14 pm
by Flamie
Code: Select all
$date = $year."-".$month."-".$day;
And if you need it back use explode()
http://www.php.net/explode
But all in all, I would strongly suggest you use unix timestamps
http://www.php.net/time with the PHP's date function
http://www.php.net/date
Posted: Fri Oct 20, 2006 4:20 pm
by feyd
Code: Select all
$date = sprintf('%04d-%02d-%02d', (int)$year, (int)$month, (int)$day);
although if it's today's date or something that's calculated,
date() is a better function to use.
Posted: Fri Oct 20, 2006 4:50 pm
by garry27
i still can't get mysql to recognise the date. i'm using:
Code: Select all
$date = date($year."-".$month."-".$day);

Posted: Fri Oct 20, 2006 5:05 pm
by Flamie
I dunno what to say man,
Did you read
http://www.php.net/date ?
You cant use the date function with the current format you have,
If you want to have the date in the format xxxx-xx-xx use either the code I gave you, or the one feyd gave you.
Code: Select all
$date = $year."-".$month."-".$day;
Posted: Fri Oct 20, 2006 5:41 pm
by RobertGonzalez
garry27 wrote:i still can't get mysql to recognise the date. i'm using:
Code: Select all
$date = date($year."-".$month."-".$day);

That's not going to work as expected. The
date() function takes a timestamp and converts to a readable date format using parameters. You are taking a date from PHP, inserting to MySQL, then pulling it out and converting back to PHP? Why not change the default date format in your MySQL table so they are always the same?