I have a database application that needs change-auditing. I am hoping to implement this at the database level so that I don't have to parse queries to see what fields are being changed or add in logging routines to existing code. Instead, I would like to add in the necessary auditing code at the DB class level.
I would like to be able to issue an UPDATE
query, and then, following that, issue another query to see what data was changed.
If the query UPDATE customers SET cus_tel = '45678', cus_name = 'Mary', cus_city = 'Cape Town' WHERE cus_id = 123;
is run, the change-detection query would return something like this:
------------------------------------------
| Field | PK | Old Value | New Value |
==========================================
| cus_tel | 123 | 12345 | 45678 |
| cus_name | 123 | John | Mary |
------------------------------------------
In this case, I'm assuming that the cus_city
field was already Cape Town
and so did not need to be updated. The PK field is useful in case a query updates multiple rows at once.
Using this data, I could then log the changes into an auditing table as required.
I am using PHP and MySQL/PDO.
EDIT
I found this SO question which addresses the issue of a trigger to log the changes to a table - almost exactly as I require:
DELIMITER $$
DROP TRIGGER `update_data `$$
CREATE TRIGGER `update_data` AFTER UPDATE on `data_table`
FOR EACH ROW
BEGIN
IF (NEW.field1 != OLD.field1) THEN
INSERT INTO data_tracking
(`data_id` , `field` , `old_value` , `new_value` , `modified` )
VALUES
(NEW.data_id, "field1", OLD.field1, NEW.field1, NOW());
END IF;
IF (NEW.field2 != OLD.field2) THEN
INSERT INTO data_tracking
(`data_id` , `field` , `old_value` , `new_value` , `modified` )
VALUES
(NEW.data_id, "field2", OLD.field2, NEW.field2, NOW());
END IF;
IF (NEW.field3 != OLD.field3) THEN
INSERT INTO data_tracking
(`data_id` , `field` , `old_value` , `new_value` , `modified` )
VALUES
(NEW.data_id, "field3", OLD.field3, NEW.field3, NOW());
END IF;
END$$
DELIMITER ;
It is clear, though, that this logs from only a single table with defined fields. Is there a way to "generalise" this trigger so that it could be applied to any arbitrary table with any arbitrary fields with no (or minimal) modification?