Triggers

Triggers are files that are included via include() statement that perform actions before or after insert, update, or delete of record.

The operation sequence is this: before, main, after. If any operation fails, not only should the next operation(s) not be executed, but the previous ones are 'rolled back' as if they never happened. If a database is not able to do this, it is not 'transaction-safe'.

Triggers are risky in basic MySQL as there is no native transaction support. It is not transaction-safe by default. There are transaction-safe table types in MySQL that can be conditionally built (see MySQL-Max), but phpMyEdit is currently not set up to support real transactions. What that means is that if an operation fails, the database may be left in an intermediate and invalid state.

The programmer must understand and accept these risks prior to using the phpMyEdit triggers mechanism. If the triggers are used, they execute within the namespace or scope of the phpMyEdit class.

Triggers must return true or false to indicate success or failure.

Example 3-16. Triggers usage

$opts['triggers']['insert']['before'] = 'categories.TIB.inc';
$opts['triggers']['insert']['after']  = 'categories.TIA.inc';
$opts['triggers']['update']['before'] = 'categories.TUB.inc';
$opts['triggers']['update']['after']  = 'categories.TUA.inc';
$opts['triggers']['delete']['before'] = 'categories.TDB.inc';
$opts['triggers']['delete']['after']  = 'categories.TDA.inc';

In every trigger file you have available following usable variables. Some from them are regarding only to particular performed action.

$this   object reference
$this->dbh   initialized MySQL database handle
$this->key   primary key name
$this->key_type   primary key type
$this->key_delim   primary key deliminator
$this->rec   primary key value (update and delete only)
$newvals   associative array of new values (update and insert only)
$oldvals   associative array of old values (update and delete only)
$changed   array of keys with changed values

There are also other variables available. For example every class property can be accessed using $this object reference. All variables occurs in 'before' triggers as well as in 'after' triggers.

It is recommended to use $this->myQuery() method in order to perform database queries for fetching additional data or doing inserts or updates to other database tables.