Nasser Nasser - 7 months ago 15
SQL Question

MySql trigger error with adding a new record

I've just learned the MySQL triggers and how they work. I decided to apply it on my small website.

I have a Users table where new users accounts are created and I would like to keep a history of adding new accounts in a UsersHistory table.

The error is that when I execute the following query, it gives me an error:

Query:

CREATE TRIGGER User_After_Insert
AFTER INSERT ON UsersHistory FOR EACH ROW WHEN NOT NEW.Deleted
BEGIN  
SET @changeType = 'DELETE';

INSERT INTO UsersHistory (UserID, changeType)
VALUES (NEW.ID, @changeType);
END;

CREATE TRIGGER User_After_Insert1
AFTER INSERT ON UsersHistory FOR EACH ROW WHEN NEW.Deleted
BEGIN  
SET @changeType = 'NEW';

INSERT INTO UsersHistory (UserID, changeType)
VALUES (NEW.ID, @changeType);
END;


The error is:


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 'WHEN NOT NEW.Deleted
BEGIN Â

SET @changeType = 'DELE' at line 1


I looked for a solution but I couldn't find.

Thanks

Answer

Have you set a DELIMITER to something different than ";"? Also, I saw some stuff I didn't know to be supported in mysql (the WHEN statements before the BEGIN blocks), so heres my suggestion:

delimiter //
CREATE TRIGGER User_After_Insert AFTER INSERT ON UsersHistory FOR EACH ROW
INSERT INTO UsersHistory (UserID, changeType) VALUES (NEW.ID, 'NEW')//
CREATE TRIGGER User_After_Delete AFTER DELETE ON UsersHistory FOR EACH ROW              
INSERT INTO UsersHistory (UserID, changeType) VALUES (OLD.ID, 'DELETE')//
delimiter ;

UPDATE

Due to your comment below, I think you need to read up on trigger a bit more mate. But here's the gist.

The above statements, create triggers in the actual database. In effect, you "install" the triggers in your database schema. Running the statements in any mysql client, will create the triggers if you have appropriate account rights.

Now, from this stage on, you dont explicitly call them from PHP or anything like that. They live in the database and are called automatically when you perform certain actions. In the above case, AFTER a record is deleted from UserHistory or AFTER a record is inserted into UserHistory.

So, when you run "INSERT INTO UserHistory VALUES ..." from your php script, the database will fire the trigger automatically.

Hope that makes sence.