PHP Prepared Statements
Prepared statements prevent SQL injection by separating SQL logic from data.
MySQLi
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "Alice";
$email = "[email protected]";
$stmt->execute();
PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([':id' => $userId]);
$user = $stmt->fetch();
Benefits
- Security — Automatic escaping prevents SQL injection
- Performance — Queries can be reused with different parameters
- Readability — Clear separation of SQL and data