What are the benefits of using placeholders in SQL queries to prevent SQL injections in PHP?

Using placeholders in SQL queries helps prevent SQL injections by separating the SQL query logic from the user input data. Placeholders are replaced with user input data by the database engine, ensuring that the input is properly sanitized and eliminating the risk of malicious SQL injection attacks.

// Using placeholders to prevent SQL injections in PHP
$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 user input data to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

// Execute the prepared statement
$stmt->execute();

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