Rick
Rick

Reputation: 2308

Set current time field for MySQL

I am trying to set the value of a field via a hidden form field to the current date and time using either PHP or Javascript that would conform to MySQL's datetime field.

Upvotes: 2

Views: 5901

Answers (5)

matthewpark319
matthewpark319

Reputation: 1263

$current = date_timestamp_set(date_create(), time());

Upvotes: 0

Matteo Alessani
Matteo Alessani

Reputation: 10412

You can directly set current date and time in your SQL insert query using NOW():

INSERT INTO table_name (current_time, column2, column3,...) 
VALUES (NOW(), value2, value3,...)

where current_time is the field where you want to put current date and time.

Upvotes: 3

Beofett
Beofett

Reputation: 2429

You can use PHP to get and format the current system date/time for use in MySQL like this:

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

Upvotes: 6

Marc B
Marc B

Reputation: 360602

<?php echo time(); ?>

will output a nice simple integer number that you can pass directly into MySQL and convert into a native mysql datetime value with FROM_UNIXTIME(). It'll save you the trouble of formatting the data in a nice YYYY-MM-DD hh:mm:ss string.

Upvotes: 1

Alan Geleynse
Alan Geleynse

Reputation: 25139

Create the column using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP

Those together will make it so that any new rows inserted have the current time and are updated again when the column is updated.

Example:

CREATE TABLE test (last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)

Edit: Nevermind, this will use a TIMESTAMP column, not DATETIME. Other answers will do what you want.

Upvotes: 2

Related Questions