title besides title

 

Thursday, November 29, 2012

PHP : Database Access - [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'));