Question:
How to insert the current date and time into a PHP mySQL database?
2007-02-05 12:19:21 UTC
I'm creating a blog website. When a user submits a new blog, I want the blog to be saved into my PHP database, along with the exact date and time that it was submitted.

For storing the date and time, I have a datetime field that is set to "not null". I've tried leaving that field blank when I'm processing a blog submission:

insert into blogs values '$title', 'body', ' ';
(notice the empty quotation marks)

but, when I do that, the field in the database is filled with zeros: 0000-00-00 00:00:00 . I'm using this field as my primary key, so I can't have them all filled with 0's!

How do I get the database to enter the current date and time? I've tried changing the field to a timestamp, but that didn't help.

I'm using PHP 5.
Three answers:
2007-02-05 12:23:59 UTC
$sql = "INSERT INTO blogs (column_name1, column_name2, column_name3) VALUES ('" . $title. "', '". $body ."', NOW())";



$result = mysql_query($sql, $db_object);



That will insert the current date and time into the 'column_name3' where 'column_name3' is the field name of your column containing the field type 'datetime'.



Because the field is of type 'datetime', you cannot use a blank space to be stored, it has to be in the pattern of '0000-00-00 00:00:00'.
?
2016-10-05 05:34:50 UTC
Php Current Time
2007-02-05 12:43:59 UTC
In addition to the suggestion above, you can also set the default value of your datetime column to be NOW() -- either through the command line or via phpMyAdmin.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...