What security measures should be implemented when dynamically loading data from a database in PHP?

When dynamically loading data from a database in PHP, it is important to implement security measures to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries, which helps to sanitize user input and avoid malicious SQL code execution.

// 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 with the actual user input
$username = $_GET['username'];
$stmt->bindParam(':username', $username);

// Execute the statement
$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>";
}