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

SQL Injection can be prevented in PHP code by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate SQL code from user input, preventing malicious SQL commands from being executed. Additionally, sanitizing and validating user input before using it in SQL queries can also help mitigate the risk of SQL Injection attacks.

// Using prepared statements to prevent SQL Injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query with a placeholder for 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 result
$result = $stmt->fetch();