What are some best practices for preventing SQL injection in PHP code?

SQL injection is a common attack where malicious SQL statements are inserted into input fields, allowing attackers to manipulate the database. To prevent SQL injection in PHP code, it is crucial to use parameterized queries with prepared statements. This approach separates SQL logic from user input, preventing attackers from injecting malicious code.

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

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

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

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

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