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.

The executeMultiple( ) method takes a two-dimensional array of values to insert:<br />

$responses = $db->executeMultiple(compiled, values);<br />

The values array must be numerically indexed from 0 and have values that are arrays<br />

of values to insert. The compiled query is executed once for every entry in values,<br />

and the query responses are collected in $responses.<br />

A better way to write the movie-insertions code is:<br />

$movies = array(array('Dr No', 1962),<br />

array('Goldfinger', 1965),<br />

array('Thunderball', 1965));<br />

$compiled = $q->prepare('INSERT INTO movies (title,year) VALUES (?,?)');<br />

$db->insertMultiple($compiled, $movies);<br />

Shortcuts<br />

PEAR DB provides a number of methods that perform a query and fetch the results<br />

in one step: getOne( ), getRow( ), getCol( ), getAssoc( ), and getAll( ). All of these<br />

methods permit placeholders.<br />

The getOne( ) method fetches the first column of the first row of data returned by an<br />

SQL query:<br />

$value = $db->getOne(SQL [, values ]);<br />

For example:<br />

$when = $db->getOne("SELECT avg(year) FROM movies");<br />

if (DB::isError($when)) {<br />

die($when->getMessage( ));<br />

}<br />

echo "The average James Bond movie was made in $when";<br />

The average James Bond movie was made in 1977<br />

The getRow( ) method returns the first row of data returned by an SQL query:<br />

$row = $db->getRow(SQL [, values ]]);<br />

This is useful if you know only one row will be returned. For example:<br />

list($title, $actor) = $db->getRow(<br />

"SELECT movies.title,actors.name FROM movies,actors<br />

WHERE movies.year=1977 AND movies.actor=actors.id");<br />

echo "($title, starring $actor)";<br />

(The Spy Who Loved Me, starring Roger Moore)<br />

The getCol( ) method returns a single column from the data returned by an SQL<br />

query:<br />

$col = $db->getCol(SQL [, column [, values ]]);<br />

The column parameter can be either a number (0, the default, is the first column), or<br />

the column name.<br />

Advanced Database Techniques | 199<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!