How can SQL Injections be prevented in PHP code, especially when handling user input?

SQL Injections can be prevented in PHP code by using prepared statements and parameterized queries when interacting with a database. This approach separates SQL logic from user input, preventing malicious SQL code from being executed. By using placeholders for dynamic data in SQL queries, the input is automatically sanitized, reducing the risk of SQL Injection attacks.

// Establish connection to the database
$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');

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

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

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