How can PHP developers prevent SQL injection vulnerabilities when querying a database for user login information?
To prevent SQL injection vulnerabilities when querying a database for user login information, PHP developers should use prepared statements with parameterized queries. This ensures that user input is treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
// Bind the user input to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the prepared statement
$stmt->execute();
// Fetch the result
$user = $stmt->fetch();