13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

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

314 Chapter 13 Advanced <strong>MySQL</strong> Programming<br />

A transaction that has been permanently written to the database is said to be committed.A<br />

transaction that is not written to the database—so that the database is reset to the state it<br />

was in before the transaction began—is said to be rolled back.<br />

Using Transactions with InnoDB<br />

By default, <strong>MySQL</strong> runs in autocommit mode.This means that each statement you execute<br />

is immediately written to the database (committed). If you are using a transactionsafe<br />

table type, more than likely you don’t want this behavior.<br />

To turn autocommit off in the current session, type<br />

set autocommit=0;<br />

If autocommit is on, you need to begin a transaction with the statement<br />

start transaction;<br />

If it is off, you do not need this comm<strong>and</strong> because a transaction will be started automatically<br />

for you when you enter an SQL statement.<br />

After you have finished entering the statements that make up a transaction, you can<br />

commit it to the database by simply typing<br />

commit;<br />

If you have changed your mind, you can revert to the previous state of the database by<br />

typing<br />

rollback;<br />

Until you have committed a transaction, it will not be visible to other users or in other<br />

sessions.<br />

Let’s look at an example. Execute the ALTER TABLE statements in the previous section<br />

of the chapter on your books database, as follows, if you have not already done so:<br />

alter table orders type=innodb;<br />

alter table order_items type=innodb;<br />

These statements convert two of the tables to InnoDB tables. (You can convert them<br />

back later if you want by running the same statement but with type=MyISAM.)<br />

Now open two connections to the books database. In one connection, add a new<br />

order record to the database:<br />

insert into orders values (5, 2, 69.98, '2008-06-18');<br />

insert into order_items values (5, '0-672-31697-8', 1);<br />

Now check that you can see the new order:<br />

select * from orders where orderid=5;

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

Saved successfully!

Ooh no, something went wrong!