문제

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.

도움이 되었습니까?

해결책

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

다른 팁

Date must have format shown to you: 0000-00-00 00:00:00

So, you have to convert it. There are thousand questions about this conversion here on SO.
The shortest way is like

list($m,$d,$y) = explode("/",$_POST['date']);
$date = mysql_real_escape_string("$y-$m-$d ".$_POST['time']);

I think the datetime format looks like this:

YYYY-MM-DD HH:MM:SS

so you've got to format your $datetime to look like that. And in your query that needs to be encapsulated in quoation marks.

  • Either you transform the string to be in the YYYY-MM-DD HH:MM:SS format yourself,
  • or you use the str_to_date() function from MySQL.

    INSERT INTO table DATETIME values (str_to_date($date,"%m/%d/%Y %h:%i"))

As far as I remember, by default, Mysql datetime should be in "yyyy-mm-dd hh:mm:ss" format.

I have added date and time in mysql db via API like this:


Call API

http://localhost/SendOrder.php?odate=20120323&otime=164545

  1. odate type is DATE
  2. otime type is TIME in DB.

It will store odate as 2012-03-23 and otime as 16:45:45.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top