Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert current date in datetime format mySQL

Tags:

php

mysql

I'm having problems getting the date inserted properly into my database.

$date = date('m/d/Y h:i:s', time()); 

I use this format, and, it echoes out correctly, however, when, I insert

mysql_query("INSERT INTO table  (dateposted)  VALUES ('$date')"); 

it doesn't appear to work successfully, and, the time remains 00:00:00 If you could find the solution that would be great, thanks.

like image 260
CCates Avatar asked Mar 02 '12 22:03

CCates


People also ask

How do I insert the current date automatically in SQL?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.

How can I get current date in database?

INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW()); If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE().

How do I get the current date in MySQL query?

MySQL CURDATE() Function The CURDATE() function returns the current date. Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).


2 Answers

If you're looking to store the current time just use MYSQL's functions.

mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())"); 

If you need to use PHP to do it, the format it Y-m-d H:i:s so try

$date = date('Y-m-d H:i:s'); mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')"); 
like image 88
Aaron W. Avatar answered Sep 26 '22 10:09

Aaron W.


Try this instead

$date = date('Y-m-d H:i:s'); 
like image 20
Erik Giberti Avatar answered Sep 25 '22 10:09

Erik Giberti