25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

168 ” Database Programming<br />

Transactions With mysqli<br />

The mysqli extension implements transaction functionality with the * commit and<br />

*rollback methods. By default, mysqli runs in auto-commit mode, which means<br />

that each database statement will be committed immediately. To disable this functionality<br />

and begin a transaction, set the auto-commit mode to FALSE using the<br />

*autocommit methods. Please note that the * autocommit methods will not work with<br />

non-transactional table types, such as MyISAM or ISAM. For these table types, all<br />

database statements are always committed immediately. See the Transactions section<br />

earlier in this chapter for more information on how transactions work.<br />

The following code illustrates the use of the transactions with mysqli. If any of the<br />

statements executed against the database fail, then the call to mysqli::commit() or<br />

mysqli_commit() will return FALSE. In this case, you can call the * rollback methods to<br />

ensure that any actions taken during the transaction are rolled back and discarded.<br />

Here, one of the INSERT statements fails to list all columns for which it has values.<br />

Thus, the commit fails and the valid INSERT statement executed earlier is not committed<br />

to the database.<br />

$mysqli->autocommit(FALSE);<br />

$mysqli->query("INSERT INTO book (isbn, title, author_id, publisher_id)<br />

VALUES (’0395974682’, ’The Lord of the Rings’, 1, 3)");<br />

$mysqli->query("INSERT INTO book (title) VALUES (’Animal Farm’, 3, 2)");<br />

if (!$mysqli->commit()) {<br />

$mysqli->rollback();<br />

}<br />

The procedural version of the code is very similar:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

mysqli_autocommit($dbh, FALSE);<br />

mysqli_query($dbh, "INSERT INTO book (isbn, title, author_id, publisher_id)<br />

VALUES (’0395974682’, ’The Lord of the Rings’, 1, 3)");<br />

mysqli_query($dbh, "INSERT INTO book (title) VALUES (’Animal Farm’, 3, 2)");<br />

if (!mysqli_commit($dbh)) {<br />

mysqli_rollback($dbh);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!