How can SQL injection be prevented in PHP when querying a database?

SQL injection can be prevented in PHP when querying a database by using prepared statements with parameterized queries. This approach allows the database to distinguish between SQL code and data, preventing malicious SQL injection attacks.

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

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

// Bind parameters
$stmt->bindParam(':username', $_POST['username']);

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

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