13.09.2016 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Foreign Keys<br />

315<br />

You should see the order displayed:<br />

+---------+------------+--------+------------+<br />

| orderid | customerid | amount | date |<br />

+---------+------------+--------+------------+<br />

| 5 | 2 | 69.98 | 2008-06-18 |<br />

+---------+------------+--------+------------+<br />

Leaving this connection open, go to your other connection <strong>and</strong> run the same select<br />

query.You should not be able to see the order:<br />

Empty set (0.00 sec)<br />

(If you can see it, most likely you forgot to turn off autocommitting. Check this <strong>and</strong> that<br />

you converted the table in question to the InnoDB format.) The reason is that the transaction<br />

has not yet been committed. (This is a good illustration of transaction isolation in<br />

action.)<br />

Now go back to the first connection <strong>and</strong> commit the transaction:<br />

commit;<br />

You should now be able to retrieve the row in your other connection.<br />

Foreign Keys<br />

InnoDB also supports foreign keys.You may recall that we discussed the concept of foreign<br />

keys in Chapter 8,“Designing Your <strong>Web</strong> Database.”When you use MyISAM tables,<br />

you have no way to enforce foreign keys.<br />

Consider, for example, inserting a row into the order_items table.You need to include<br />

a valid orderid. Using MyISAM, you need to ensure the validity of the orderid you<br />

insert somewhere in your application logic. Using foreign keys in InnoDB, you can let<br />

the database do the checking for you.<br />

How do you set this up? To create the table initially using a foreign key, you could<br />

change the table DDL statement as follows:<br />

create table order_items (<br />

orderid int unsigned not null references orders(orderid),<br />

isbn char(13) not null,<br />

quantity tinyint unsigned,<br />

primary key (orderid, isbn)<br />

) type=InnoDB;<br />

We added the words references orders(orderid) after orderid.This means this column<br />

is a foreign key that must contain a value from the orderid column in the orders<br />

table.<br />

Finally, we added the table type type=InnoDB at the end of the declaration.This is<br />

required for the foreign keys to work.

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

Saved successfully!

Ooh no, something went wrong!