Prepared Statements
A Prepared Statement (parameterized statement) is created with a query template using placeholders (?) instead of providing actual values. The placeholders are later replaced with actual values that are bound to the parameters in the statement during execution.
PHP 8.0
SELECT
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
INSERT
$stmt = $mysqli->prepare("INSERT INTO users (email, password) VALUES (?,?)");
$stmt->execute([$email, $password_hash]);
UPDATE
$stmt = $mysqli->prepare("UPDATE users SET name=?, email=?, password=? WHERE id=?");
$stmt->execute([$name, $email, $password, $id]);
DELETE
$stmt = $mysqli->prepare("DELETE FROM users WHERE id=?");
$stmt->execute([$id]);
PHP 7.X
Binding Parameters
A prepared statement also provides protection against SQL injection as the query is created with placeholders that are replaced with input values later during 'bind param' and 'execute'. There is also no need of escaping input values as the values are treated as literals avoiding the threat an SQL injection.
There are four types of binding allowed regarding variables:
"i" - Integer, "d" - Doubles, "b" - Blob, "s" - String
INSERT
$sql = "SELECT * FROM tablename WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();
UPDATE
$sql = "UPDATE tablename SET name = ?, quantity = ?, price = ? WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sidi", $_POST['name'], $_POST['quantity'], $_POST['price'], $_POST['id']);
if($stmt->execute()){
return true;
}
INSERT
$sql = "INSERT INTO tablename (name, quantity, price) VALUES (?, ?, ?)"
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sid", $_POST['name'], $_POST['quantity'], $_POST['price']);
if($stmt->execute()){
return true;
}
DELETE
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $_POST['id']);
if($stmt->execute()){
return true;
}