Insert date and time into Mysql

时间秒杀一切 提交于 2019-12-18 11:30:23

问题


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.


回答1:


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



回答2:


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']);



回答3:


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.




回答4:


  • 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"))




回答5:


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




回答6:


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.



来源:https://stackoverflow.com/questions/2930059/insert-date-and-time-into-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!