Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a revision history with PHP and MySQL

Tags:

php

mysql

I have a couple tables that I want to keep a revision history on. What is the best way to accomplish this? It's going to be several fields (20 or so).

Should I create a duplicate table and just submit the old data to that? Should I use triggers? Or should I create a separate table and just track the changes made?

like image 954
Keith Avatar asked Nov 08 '11 13:11

Keith


People also ask

How to keep history of record updates in MySQL?

Create a table called changes . It would contain the same fields as the master table but prefixed with old and new, but only for those fields which were actually changed and a TIMESTAMP for it. It would be indexed with an ID . This way, a SELECT report could be run to show the history of each record.

Does MySQL have change tracking?

MySQL binary logs provide a very efficient way to track data changes for MySQL CDC. They contain events that describe the modifications to data. In short, binary logs contain all the information that is required to trace the global status of the server right from the time it was started.

How do I permanently save data in MySQL?

We can use COMMIT command to make the changes, made in a current transaction, permanently recorded in MySQL database. Suppose if we run some DML statements and it updates some data objects, then COMMIT command will record these updates permanently in the database.

What can you use to detect changes on MySQL table and run additional operations after them?

A common way to detect changes to a table between runs is with a query like this: SELECT COUNT(*),MAX(t) FROM table; But for this to work, a few assumptions must be true about your table: The t column has a default value of NOW()


1 Answers

We're pretty happy with our choice which is using two tables per versioned entity.

Tables would look similar to this:

Table person:

  • id (PK)
  • version (counter for optimistic locking)
  • current (foreign key referencing person_version)
  • ... (any property that won't change)

Table person_version:

  • id (PK)
  • person (not null) (foreign key referencing person)
  • timestamp (used for sorting)
  • ... (any property that might change)

As entries in person_version won't ever change, it's easy to cache them (as long as there aren't any references to tables that might change)

like image 147
sfussenegger Avatar answered Sep 20 '22 01:09

sfussenegger