05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

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

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

foreach ($movies as $movie) {<br />

$id = $db->nextID('movies');<br />

splice($movie, 0, 0, $id);<br />

$db->query('INSERT INTO movies (id,title,year) VALUES (?,?,?)', $movie);<br />

}<br />

A sequence is really a table in the database that keeps track of the last-assigned ID.<br />

You can explicitly create and destroy sequences with the createSequence( ) and<br />

dropSequence( ) methods:<br />

$res = $db->createSequence(sequence);<br />

$res = $db->dropSequence(sequence);<br />

The result will be the result object from the create or drop query, or DB_ERROR if an<br />

error occurred.<br />

Metadata<br />

The getListOf( ) method lets you query the database for information on available<br />

databases, users, views, and functions:<br />

$data = $db->getListOf(what);<br />

The what parameter is a string identifying the database feature to list. Most databases<br />

support "databases"; some support "users", "views", and "functions".<br />

For example, this stores a list of available databases in $dbs:<br />

$dbs = $db->getListOf("databases");<br />

Transactions<br />

Some RDBMSs support transactions, in which a series of database changes can be<br />

committed (all applied at once) or rolled back (discarded, with the changes not applied<br />

to the database). For example, when a bank handles a money transfer, the withdrawal<br />

from one account and deposit into another must happen together—neither should<br />

happen without the other, and there should be no time between the two actions.<br />

PEAR DB offers the commit ( ) and rollback( ) methods to help with transactions:<br />

$res = $db->commit( );<br />

$res = $db->rollback( );<br />

If you call commit( ) or rollback( ) on a database that doesn’t support transactions,<br />

the methods return DB_ERROR.<br />

Sample Application<br />

Because web database applications are such a mainstay of web development, we’ve<br />

decided to show you a complete sample application in this chapter. This section<br />

develops a self-maintaining business listing service. Companies add their own records<br />

to the database and pick the category or categories by which they want to be indexed.<br />

202 | Chapter 8: Databases<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!