A Prepared Statement is a programming technique, especially used when working with databases, to make SQL queries more secure and efficient.
It consists of two steps:
Prepare the SQL query with placeholders
Example in SQL:
SELECT * FROM users WHERE username = ? AND password = ?
(Some languages use :username
or other types of placeholders.)
Bind parameters and execute
The real values are bound later, for example:
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
✅ Protection against SQL injection:
User input is treated separately and safely, not directly inserted into the SQL string.
✅ Faster with repeated use:
The SQL query is parsed once by the database server and can be executed multiple times efficiently (e.g., in loops).
$conn = new mysqli("localhost", "user", "pass", "database");
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email); // "s" stands for string
$email = "example@example.com";
$stmt->execute();
$result = $stmt->get_result();
A Prepared Statement separates SQL logic from user input, making it a secure (SQL Injection) and recommended practice when dealing with databases.