start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

10.7. Modifying Data in a SQL Database

10.7.1. Problem

You want to add, remove, or change data in a SQL database.

10.7.2. Solution

With PEAR DB, use DB::query( ) to send an INSERT, DELETE, or UPDATE command:

$dbh->query("INSERT INTO family (id,name) VALUES (1,'Vito')");

$dbh->query("DELETE FROM family WHERE name LIKE 'Fredo'");

$dbh->query("UPDATE family SET is_naive = 1 WHERE name LIKE 'Kay'");

You can also prepare a query with DB::prepare( ) and execute it with DB::execute( ):

$prh = $dbh->prepare('INSERT INTO family (id,name) VALUES (?,?)');
$dbh->execute($prh,array(1,'Vito'));

$prh = $dbh->prepare('DELETE FROM family WHERE name LIKE ?');
$dbh->execute($prh,array('Fredo'));

$prh = $dbh->prepare('UPDATE family SET is_naive = ? WHERE name LIKE ?');
$dbh->execute($prh,array(1,'Kay');

10.7.3. Discussion

The query( ) method sends to the database whatever it's passed, so it can be used for queries that retrieve data or queries that modify data.

The prepare( ) and execute( ) methods are especially useful for queries that you want to execute multiple times. Once you've prepared a query, you can execute it with new values without re-preparing it:

$prh = $dbh->prepare('DELETE FROM family WHERE name LIKE ?');
$dbh->execute($prh,array('Fredo'));
$dbh->execute($prh,array('Sonny'));
$dbh->execute($prh,array('Luca Brasi'));

10.7.4. See Also

Recipe 10.4 for connecting to a SQL database; Recipe 10.5 for querying a SQL database; Recipe 10.8 discusses prepare( ) and execute( ) in detail; documentation on DB::query( ) at http://pear.php.net/manual/en/core.db.query.php, DB::prepare( ) at http://pear.php.net/manual/en/core.db.prepare.php, and DB::execute( ) at http://pear.php.net/manual/en/core.db.execute.php.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.