Sending SQL Via PDO
$stmt = $db->prepare($sql);
$stmt->execute();
|
To send SQL via PDO, a statement must be executed using the query() method. As always, you need a way to escape special characters. This can, once again, be done using prepared statements. First, an SQL query can be parsed using a method called prepare(), whereas placeholders start with a colon. Then, the bindParam() method binds a value to a placeholder name. Finally, the execute() method sends the statement to the database.
Sending SQL Via PDO (pdo_execute.php; excerpt)
<?php
try {
$db = new PDO('sqlite:PDOquotes.db');
require_once 'stripFormSlashes.inc.php';
$sql = 'INSERT INTO quotes (quote, author, year)
VALUES (:quote, :author, :year)';
$stmt = $db->prepare($sql);
$stmt->bindParam('quote', $_POST['quote']);
$stmt->bindParam('author', $_POST['author']);
$stmt->bindParam('year',
intval($_POST['year']));
$stmt->execute();
echo 'Quote saved.';
} catch (PDOException $ex) {
echo 'Connection failed: ' . htmlspecialchars
($ex->getMessage());
}
?>
|