I am trying to insert date and time into mysql datetime field. When a user select a date and time, it will generate two POST variables. I have searched internet but still not sure how to do it.
My code.
//date value is 05/25/2010
//time value is 10:00
$date=$_POST['date'];
$time=$_POST['time'];
$datetime=$date.$time
If I insert $datetime into mysql, the date appears to be 0000-00-00:00:00:00
I appreciate it if anyone could help me about this. Thanks.
The CURRENT_TIMESTAMP function in the MySQL database returns the current date and time (i.e. the time for the machine running that instance of MySQL). It is given as a value in the 'YYYY-MM-DD hh:mm:ss' format.
The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD.
You can use str_to_date to convert a date string to MySQL's internal date format for inserting.
$datetime = $_POST['date'] . ' ' . $_POST['time'] . ':00';
$datetime = mysql_real_escape_string($datetime);
$query = "INSERT INTO table(timestamp) VALUES ('$datetime')";
alternative solution that can handle more formats:
$datetime = $_POST['date'] . ' ' . $_POST['time'];
$datetime = mysql_real_escape_string($datetime);
$datetime = strtotime($datetime);
$datetime = date('Y-m-d H:i:s',$datetime);
$query = "INSERT INTO table(timestamp) VALUES ('$datetime')";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With