How can PHP scripts be modified to prevent SQL injection attacks when retrieving data from a database?

To prevent SQL injection attacks when retrieving data from a database in PHP scripts, developers should use prepared statements with parameterized queries. This approach separates SQL logic from user input, making it impossible for malicious input to alter the SQL query structure. By binding parameters to the query, developers can ensure that user input is treated as data rather than executable code.

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

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

// Bind the parameter and execute the query
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

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

// Loop through the results and display them
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}