You want to add, remove, or change data in an SQL database.
Use PDO::exec() to send an INSERT, DELETE, or UPDATE command, as shown in Example 10-14.
Example 10-14. Using PDO::exec()
1 2 3 4 5 |
$db->exec("INSERT INTO family (id,name) VALUES (1,'Vito')"); $db->exec("DELETE FROM family WHERE name LIKE 'Fredo'"); $db->exec("UPDATE family SET is_naive = 1 WHERE name LIKE 'Kay'"); |
You can also prepare a query with PDO::prepare() and execute it with PDOStatement::execute(), as shown in Example 10-15.
Example 10-15. Preparing and executing a query
1 2 3 4 5 6 7 8 |
$st = $db->prepare('INSERT INTO family (id,name) VALUES (?,?)'); $st->execute(array(1,'Vito')); $st = $db->prepare('DELETE FROM family WHERE name LIKE ?'); $st->execute(array('Fredo')); $st = $db->prepare('UPDATE family SET is_naive = ? WHERE name LIKE ?'); $st->execute(array(1,'Kay')); |
The exec() method sends to the database whatever it’s passed. For INSERT, UPDATE, and DELETE queries, it returns the number of rows affected by the query.
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 repreparing it. Example 10-16 reuses the same prepared query three times.
Example 10-16. Reusing a prepared statement
1 2 3 4 |
$st = $db->prepare('DELETE FROM family WHERE name LIKE ?'); $st->execute(array('Fredo')); $st->execute(array('Sonny')); $st->execute(array('Luca Brasi')); |