Skip to content
PHP Logo

How can SQL injection vulnerabilities be mitigated in PHP code when querying a database?

SQL injection vulnerabilities can be mitigated in PHP code by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL commands from being executed. By binding parameters to placeholders in the query, the database engine can distinguish between code and data, effectively neutralizing SQL injection attacks.

php
// 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 query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();