views:

153

answers:

4

I want to store the timestamp which a row was inserted into a MySQL table with the row, to be later compared to other times. What's the best field type for this and what's the best way to insert the row with the timestamp in PHP?

A: 

Use TIMESTAMP NOT NULL

When you do an INSERT and leave out that column, it will default to CURRENT_TIMESTAMP

Matt
+1, Why was this down-voted?
Alix Axel
I didn't downvote, but `TIMESTAMP NOT NULL` only means that the column can never have a null value; you need a `DEFAULT` constraint to ensure the column is populated on insert.
OMG Ponies
A: 

Use the DateTime datatype for the column, the NOW() function to set the current time and the UNIX_TIMESTAMP() function if you need to compare it using PHP

Andrew G. Johnson
+1, Why was this down-voted?
Alix Axel
A: 

Use TIMESTAMP as the field type. All TIMESTAMP field types will have CURRENT_TIMESTAMP as the default (which is a alias for NOW())

While adding a record, write '' to that field - it will take the default time as the value.

Crimson
+3  A: 

Use TIMESTAMP DEFAULT CURRENT_TIMESTAMP. This will create a TIMESTAMP field that is set on INSERT, but not on UPDATE.

Ignacio Vazquez-Abrams
When I retrieve the value with PHP, how do I make it return as the number of seconds since the reference date?
Chetan
@Chetan, SELECT UNIX_TIMESTAMP(updated_at) as updated_at FROM Table;
vava
In your `SELECT` query, add another column.. `now()-timestamp_column as difference`
Matt
@vava: That returns the unix timestamp value, not the difference in seconds since the current date.
OMG Ponies
I have a `SELECT *` query and I access the return values by index in the array that is generated. Is there any way to use the same `SELECT *` query without having to have a seperate `now()-timestamp_column as difference` query?
Chetan
Never mind, I can just use `strtotime()` to achieve the same effect.
Chetan