Code has been added to clipboard!
Prepared Statements With PHP PDO
Example
<?php
$host = 'host';
$user = 'user';
$pass = 'pass';
$db = 'db';
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//bind parameters and prepare sql
$stmt = $conn->prepare("INSERT INTO users (name, surname, email) VALUES (:name, :surname, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':email', $email);
// insert a row
$name = "John";
$surname = "Doe";
$email = "[email protected]";
$stmt->execute();
// insert another row
$name = "Mary";
$surname = "Moe";
$email = "[email protected]";
$stmt->execute();
// insert another row
$name = "Julie";
$surname = "Dooley";
$email = "[email protected]";
$stmt->execute();
echo "New records created successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>