Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert current date/time using now() in a field using MySQL/PHP

Since MySQL evidently cannot automatically insert the function now() in a datetime field in adding new records like some other databases, based on comments, I'm explicitly trying to insert it using an SQL statement. (People seem to think timestamp with curdate() is not the answer due to the various limitations of timestamp.) There are numerous articles on the web suggesting inserting now() using SQL should work.

When I try to insert the date time using the SQL statement, however, the field does not populate with the current time/date, but it only gives me the default 0000-00-, etc. This is probably a syntax error, but it's driving me crazy, so I am posting it.

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())";  

It inserts first and last, but nothing for when added, leaving 0000-00-00, etc. in the whenadded field.

The field type is datetime, it has no collation, attributes, null default or extra. BTW, I tried putting now() in single quotes... It threw an error.

like image 931
user1260310 Avatar asked Mar 23 '12 14:03

user1260310


People also ask

How do I insert the current date in a column in SQL?

To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method. Insert both date and time with the help of now().

How can we get current date and time in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS.

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

Introduction to MySQL DATE data type This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want. MySQL uses 3 bytes to store a DATE value.


2 Answers

NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:

date('Y-m-d H:i:s') 

But I wouldn't recommend this.

like image 103
Ronan Avatar answered Sep 24 '22 12:09

Ronan


You forgot to close the mysql_query command:

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");

Note that last parentheses.

like image 30
ckwolfling Avatar answered Sep 24 '22 12:09

ckwolfling