Reputation: 14250
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.
Upvotes: 11
Views: 42500
Reputation: 1
I have added date and time in mysql db via API like this:
Call API
http://localhost/SendOrder.php?odate=20120323&otime=164545
odate
type is DATEotime
type is TIME in DB.It will store odate as 2012-03-23 and otime as 16:45:45.
Upvotes: 0
Reputation: 39763
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"))
Upvotes: 2
Reputation: 157828
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']);
Upvotes: 4
Reputation: 42350
$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')";
Upvotes: 7
Reputation: 37354
As far as I remember, by default, Mysql datetime should be in "yyyy-mm-dd hh:mm:ss" format.
Upvotes: 1
Reputation: 5837
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.
Upvotes: 3