Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set field to automatically insert time-stamp on UPDATE?

Tags:

mysql

triggers

I have a table with a DEC field named product_price and I wanted to add a field called price_updated_date. Is there a way to set the table to automatically insert the current time-stamp whenever the product_price field has been updated?

If not, is there a way to set it to insert the current time-stamp any time the entry is updated at all?

update:

It seems like using a trigger is the best option here. I am new to triggers and having some trouble creating it. Here is my code:

CREATE TRIGGER price_update
AFTER UPDATE ON cart_product
FOR EACH ROW
IF(OLD.product_price != NEW.product_price)
THEN
UPDATE cart_product 
SET price_updated_date = CURDATE()
WHERE product_id = NEW.product_id

This is giving me this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8

like image 324
JD Isaacks Avatar asked Nov 22 '10 15:11

JD Isaacks


Video Answer


1 Answers

Why not set properties for that field as:

DEFAULT CURRENT_TIMESTAMP 
ON UPDATE CURRENT_TIMESTAMP;
like image 95
user1160862 Avatar answered Oct 07 '22 02:10

user1160862