Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 985
FlyingCat Avatar asked May 28 '10 14:05

FlyingCat


People also ask

How do you display time and date in MySQL?

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.

How do you insert a date in MySQL?

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.

How do I insert date in YYYY-MM-DD format in MySQL?

You can use str_to_date to convert a date string to MySQL's internal date format for inserting.


1 Answers

$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')";
like image 177
GSto Avatar answered Oct 11 '22 02:10

GSto