Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store php datetime in mysql database

Tags:

php

mysql

I can't believe I can't do this, but I want to be able to store the current date and time from php in to a mysql table.

The column in the table is type datetime. I've tried this

$current_date = date("Y-m-d"); $my_date = strtotime($current_date); INSERT INTO my_table (date_time) VALUES ('$my_date') 

but my timestamp comes up as 0000-00-00 00:00:00

This must be so easy to do but I just can't get it working! I want to use the timestamp from php rather than using the mysql now() function

like image 688
Damian Avatar asked Dec 02 '12 16:12

Damian


People also ask

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

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.

How does MySQL store datetime?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

How can I insert current date in MySQL using PHP?

The simplest method to insert the current date and time in MySQL is to use the now() function. Once you call the function, it returns the current date and time in the system's configured time zone as a string. The value returned from the now() function is YYYY-MM-DD for the date and HH-MM-SS-UU for the time record.

How can add date and time in database in PHP?

$d=mktime(11, 14, 54, 8, 12, 2014); echo "Created date is " . date("Y-m-d h:i:sa", $d);


2 Answers

Try this:

$my_date = date("Y-m-d H:i:s"); INSERT INTO my_table (date_time) VALUES ('$my_date'); 

In the date-format parameter of the date function, use :
'H' for 24hr format
'h' for 12hr format

like image 72
CoursesWeb Avatar answered Sep 20 '22 17:09

CoursesWeb


Don't save it as the Unix Timestamp (which strtotime() outputs), but as "2012-12-02 13:00" into the DATETIME column.

like image 39
chrki Avatar answered Sep 20 '22 17:09

chrki