How can SQL injection vulnerabilities be mitigated in PHP scripts, particularly when querying a database for user information?
SQL injection vulnerabilities can be mitigated in PHP scripts by using prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query. By binding parameters to placeholders in the query, the database system 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 placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch the results
$user = $stmt->fetch();