chris05
chris05

Reputation: 745

Save date/time from PHP to SQL

I want to save the date and time from PHP to SQL. Here is the SQL statement to insert new record (found in a method within a class):

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
            value (:headline, :text, :date, :rating, :product_id, :username)

And in my .php page, I call the current date and time using $_SERVER['REQUEST_TIME']. But still I'm getting the error "Incorrect datetime value". What can I use to get the date?

Upvotes: 2

Views: 25093

Answers (6)

MichD
MichD

Reputation: 1180

You can use SQL's own CURRENT_TIMESTAMP value to get an automatically formatted timestamp.

As for $_SERVER['REQUEST_TIME'], you can just use time() or microtime() instead.

As mentioned, REQUEST_TIME, as well as time() and microtime() return a UNIX timestamp, which is basically the amount of seconds that have passed since the UNIX epoch, which is not the same format as a DATETIME field expects.

Upvotes: 0

Ryan Stortz
Ryan Stortz

Reputation: 393

date_default_timezone_set('US/Eastern');
$cur_date=date("Y-m-d");

Upvotes: 0

Andre Martov
Andre Martov

Reputation: 77

If you need the current time you can do it like that:

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
INSERT INTO tbl_reviews ('$headline', '$text', CURDATE(), '$rating', '$product_id', '$username');

Upvotes: 0

dana
dana

Reputation: 5208

it is only a guess, but $_SERVER['REQUEST_TIME'] returns a float, not a valid datetime format.

Upvotes: 0

Mithrandir
Mithrandir

Reputation: 25357

Does it have to be the exact request time? You could make your life easier and simply use:

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
            value (:headline, :text, now(), :rating, :product_id, :username)

MySQL inserts the current date as soon your entry is written to the table.

Upvotes: 4

Ben D
Ben D

Reputation: 14479

Your timestamp can be generated:

$timestamp = date('Y-m-d H:i:s');

This should mimic the mysql timestamp and datetime formats.

Assuming that the mysql has its timestamp synchronized with the php server in question, you can also just use the mysql current timestamp functions:

NOW() or CURRENT_TIMESTAMP or CURRENT_TIMESTAMP()

Upvotes: 6

Related Questions