How can you prevent SQL injection when retrieving data from a database in PHP?

SQL injection can be prevented in PHP by using prepared statements and parameterized queries. This involves using placeholders in the SQL query and binding variables to those placeholders before execution. This ensures that user input is treated as data and not as part of the SQL query, thus preventing malicious SQL injection attacks.

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

// Prepare a SQL query with a placeholder
$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 results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}