How can SQL injections be prevented when using variables in queries in PHP?

SQL injections can be prevented by using parameterized queries in PHP. By using prepared statements and binding parameters, you can ensure that user input is treated as data rather than executable code. This helps to protect your database from malicious SQL injection attacks.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

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