Why is it recommended to use Prepared Statements instead of mysqli_real_escape_string for preventing SQL injection in PHP?
Using Prepared Statements is recommended over using mysqli_real_escape_string for preventing SQL injection in PHP because Prepared Statements separate the SQL query from the user input, preventing any malicious input from altering the query structure. This method also automatically handles escaping of special characters, making it more secure and easier to use compared to manually escaping each input value with mysqli_real_escape_string.
// Using Prepared Statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
// Bind parameters
$stmt->bind_param("ss", $username, $password);
// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
// Fetch results
$result = $stmt->get_result();
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();