What are the best practices for preventing SQL injection in PHP applications?

SQL injection is a common attack where malicious SQL queries are inserted into input fields, allowing attackers to manipulate the database. To prevent SQL injection in PHP applications, developers should use prepared statements with parameterized queries instead of concatenating user input directly into SQL queries.

// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();