How can SQL injection vulnerabilities be avoided in PHP code when querying a database?
SQL injection vulnerabilities can be avoided in PHP code by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious input from being executed as SQL commands. By binding parameters to placeholders in the query, the database engine can distinguish between code and data, effectively preventing SQL injection attacks.
// 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 query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();