A **Prepared Statement** is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Most importantly, it is the standard defense against **SQL Injection** attacks.
?).In MySQLi, you use prepare() and then bind_param() to link your variables.
<?php
$stmt = $conn->prepare("INSERT INTO Users (firstname, lastname, email) VALUES (?, ?, ?)");
// "sss" means the three parameters are all strings
$stmt->bind_param("sss", $firstname, $lastname, $email);
// Set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
i - integerd - doubles - stringb - blobPDO is even more powerful because it supports **Named Parameters**, which make your code much more readable.
<?php
try {
$stmt = $conn->prepare("INSERT INTO Users (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// Insert one row
$firstname = "Jane";
$lastname = "Smith";
$email = "jane@example.com";
$stmt->execute();
echo "New record created successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
execute() method in PDO, skipping the bindParam() calls entirely!
?).:name).$conn->query("... WHERE id = $id").
We've covered the core PHP & MySQL operations! Now let's dive into **Advanced Topics**, starting with how PHP handles **JSON** data.