How can SQL injection be prevented when executing database queries in PHP?
SQL injection can be prevented in PHP by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database system can differentiate between code and data, effectively mitigating the risk of SQL injection attacks.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
// Bind parameters to placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the statement
$stmt->execute();