How to use LOCK or TRANSACTION for InnoDB Engine

Run command window:

c:\xampp\mysql\bin>
command:mysql -u username -p password

Then the commands below can be used to lock/unlock table(s).

LOCK TABLES databasename.table1 WRITE, databasename.table2 WRITE;
UNLOCK TABLES;

The command is used to show the status:
SHOW ENGINE INNODB STATUS;

Below is the code to use transaction:
// Transaction
$transaction = db_transaction();

try {
db_query(‘LOCK TABLES table1 WRITE, table2 WRITE;’);
$result_list = db_query($SQL_insert);
$SQL_qurey = “select LAST_INSERT_ID() as ID”;

$tmp_result_1 = db_query($SQL_qurey);

foreach ($tmp_result_1 as $record)
$field_value_1 = $record->ID;

$SQL_insert = “INSERT INTO `table2` (`field1`, `field2`) VALUES (‘$field_value_2’, ‘$field_value_2’)”;

db_query($SQL_insert);
db_query(‘UNLOCK TABLES;’);
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception(‘Transaction’, $e);
}
// End of Transaction

Leave a Reply

Your email address will not be published. Required fields are marked *