How can prepared statements in PHP help prevent SQL injection when interacting with a database?
Prepared statements in PHP help prevent SQL injection by separating SQL code from user input. This means that user input is treated as data and not as part of the SQL query, making it impossible for an attacker to inject malicious SQL code.
// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = "example_user";
$stmt->execute();
// Get results
$result = $stmt->get_result();
// Fetch data
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close statement and connection
$stmt->close();
$mysqli->close();