The PDO prepare() method is used to create SQL statements that can be safely executed multiple times with different values. It enhances performance and provides strong protection against SQL injection.
The prepare() method returns a prepared statement object. Parameters are represented using placeholders, which are replaced securely during execution.
// Establish database connection using PDO
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement with named placeholders
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
// Execute prepared statement with secure values
$stmt->execute([':name' => 'John Doe', ':email' => 'john@example.com']);
echo "Record inserted successfully!";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
When executed successfully, the script inserts a new record into the database and displays a confirmation message. If an error occurs, it is safely handled using exception handling.
This flow illustrates how prepared statements work: