How can PHP developers avoid SQL injection vulnerabilities when constructing SQL queries in their code?
To avoid SQL injection vulnerabilities, PHP developers should use prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, developers can ensure that user input is treated as data rather than executable code.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the parameter to a variable
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();