How can PHP developers handle SQL injections and prevent unintended consequences in database queries?

SQL injections can be prevented by using prepared statements with parameterized queries in PHP. This technique separates SQL code from user input, preventing malicious SQL code from being executed. By using prepared statements, PHP developers can ensure that user input is treated as data rather than executable code.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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