0

I have several tables in the database: Users, Profiles, Articles

I also have one table called Changes, which is used for administrative purposes. This table consists of id, table_name, and date_created. What I need to do is whenever something is added, deleted or updated in a regular table (Users, Profiles, Articles), create a new row in the Changes with the name of the updated table and the current timestamps.

I've been browsing for a while and tried many different methods, but nothing really worked. I know the solution should be very simple, may be someone can help me. Thank you for your time.

2

2 Answers 2

1

So in this case you need 9 trigger 3 for each of the regular table after insert, after update, after delete

Here is for one table you can write for the others

When you insert on Users

delimiter //
create trigger log_user_insert after insert on Users
for each row 
begin
  insert into Changes (table_name,date_created) values ('Users',now());
end; //

delimiter ;

When update happens on Users

delimiter //
create trigger log_user_update after update on Users
for each row 
begin
  insert into Changes (table_name,date_created) values ('Users',now());
end; //

delimiter ;

When delete happens on Users

delimiter //
create trigger log_user_update after delete on Users
for each row 
begin
  insert into Changes (table_name,date_created) values ('Users',now());
end; //

delimiter ;

I would suggest to add a column called action in the table Changes and to insert each action name as well i.e. insert,update and delete.

Sign up to request clarification or add additional context in comments.

1 Comment

OMG, it seem to work! 'Dobby is free' :) Now I can have some sleep. Thank you, man!
0

You need to create an update, insert and delete trigger on each of the data tables:

CREATE TRIGGER upd_changes_users BEFORE UPDATE ON Users
FOR EACH ROW
 BEGIN
     INSERT INTO changes (table_name, date_created) VALUES ('users', NOW());
 END;

This code assumes, that the id column in changes is auto_generated. You might also want to consider including a type column in the changes table (to differentiate between insert, update and delete).

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.