11

Say I have a table name auto_parts with these fields. id, part, price, timestamp and I insert a new row via php as so:

$query = "insert into auto_parts(id, part, price, timestamp)
  values(1, 'axle', 200)"
mysql_query($query);

will that automatically add the timestamp. Or do I have to insert a value for timestamp myself?

1
  • What is your table structure? Commented Dec 29, 2011 at 3:39

4 Answers 4

24

What you need to do is declare timestamp to be of type in your sql

timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

and modify the query to

$query = "insert into auto_parts(id, part, price)
  values(1, 'axle', 200)"
mysql_query($query);
Sign up to request clarification or add additional context in comments.

2 Comments

you can use only one timestamp variable per table !!
Only one automatic timestamp per table, whether via DEFAULT or UPDATE (though I think that's changed in recent MySQL versions). You can have multiple timestamp columns, as long as no more than one is set/updated automatically. dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
11
$query = "insert into auto_parts(id, part, price, timestamp)
  values(1, 'axle', 200, 'NOW()')"
mysql_query($query);

1 Comment

It is convenient when you have more than 1 timestamp column (and one is automatic, see Sven Viking comment for details) and want to update/insert a new data in one other timestamp column.
1

Do it in SQL itself instead of passing it ... its more efficient ... This is the corresponding post:

Auto TimeStamp new entry to DB (phpMyAdmin)

Comments

0

I know there are already answers to this question so I am kind of combining all answers and explaining a little bit. There may be two ways to do this,

  1. Change your table and make timestamp column to default CURRENT_TIMESTAMP

ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

and modify your query like this, timestamp will be inserted automatically

$query = "insert into auto_parts(id, part, price) values(1, 'axle', 200)"; mysql_query($query);

  1. If you have more than one timestamp table then you can make one as current timestamp and for other one use like this

ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL

and modify your query like this

$query = "insert into auto_parts(id, part, price, timestamp) values (1, 'axle', 200, now())"; mysql_query($query);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.