Search code examples
phpmysqlloggingaudit-logging

Method to record what activities are performed on Database? -MySQL / PHP


I have decided to create a new table in my database that will be used for auditing all actions performed on my database.

My table "activity" is fairly simple and contains the following columns:

  • activity_id - the primary key
  • user_id - foreign key of the user
  • action - type of query being performed (SELECT, UPDATE, DELETE)
  • table - name of affected table
  • row - name of affected row(s)

What I am doing at the moment is when a query is performed I then have another query after it which inserts information into my "activity" table.

CODE:

//query
$db->query("DELETE FROM foo WHERE id = '$foo->id'");
//activity record query
$db->query("INSERT INTO acitivity ( user_id, action, table, row ) VALUES ('$user->id', 'Deleted' , '$foo->id', 'foo')");

As you can see I am having to do this manually for each query and I have over 100 queries in my system and I really don't want to have to type a individual query to record what happens.

I was wondering is there any features in MySQL that can tell me what actions have been performed or is there any libraries or techniques in PHP that can help me?

Or am I doomed to write out 100 individual queries in my system?

Thanks


Solution

  • Create ON INSERT, ON_UPDATE and ON_DELETE triggers for your table that write details of all changes to an audit activity table