phpmysqldatetimedateinsert-id

Insert date and time into Mysql


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.


Solution

  • $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')";