How can SQL Injections be prevented in PHP code when querying a database for user credentials?
SQL Injections can be prevented in PHP code when querying a database for user credentials by using prepared statements with parameterized queries. This method ensures that user input is treated as data rather than executable code, 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', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);
// Execute the query
$stmt->execute();
// Fetch the result
$user = $stmt->fetch();