MySQL triggers: How to find out the name of the table and the field that was updated / deleted, due to which the trigger worked

Question:

The task is as follows: when updating a table record, you need to create a trigger that will add to the user's change table, table name, field name, action and update time.

Here is the code for the SQL query for creating a trigger:

DELIMITER $$
CREATE TRIGGER upd_check
AFTER UPDATE ON xyz_clients FOR EACH ROW 
BEGIN 
INSERT INTO xyz_changes(user, table_name, record, action, date) 
VALUES(CURRENT_USER, ???, ???, 'update', CURRENT_DATE); 
END

You need to somehow get the title of the updated page and post. Thanks in advance for your help.

Answer:

Because in MySQL one trigger can be attached to only one table, then you know its name – this is xyz_clients

The name of the changed field is a little more complicated. You need to check if this particular field has changed

CREATE TRIGGER upd_check
AFTER UPDATE ON xyz_clients FOR EACH ROW 
BEGIN
  IF (NOT OLD.field1 <=> NEW.field1) THEN
    INSERT INTO xyz_changes(user, table_name, record, action, date) 
    VALUES(CURRENT_USER, 'xyz_clients', 'field1', 'update', CURRENT_DATE); 
  END IF;
  IF (NOT OLD.field2 <=> NEW.field2) THEN
    INSERT INTO xyz_changes(user, table_name, record, action, date) 
    VALUES(CURRENT_USER, 'xyz_clients', 'field2', 'update', CURRENT_DATE); 
  END IF;
  ..................
  IF (NOT OLD.fieldN <=> NEW.fieldN) THEN
    INSERT INTO xyz_changes(user, table_name, record, action, date) 
    VALUES(CURRENT_USER, 'xyz_clients', 'fieldN', 'update', CURRENT_DATE); 
  END IF;
END
Scroll to Top