How can placeholders be effectively used to replace dynamic content retrieved from a database in PHP?

When retrieving dynamic content from a database in PHP, placeholders can be effectively used to prevent SQL injection attacks and ensure secure data handling. By using prepared statements with placeholders, you can separate SQL logic from user input, allowing the database to distinguish between code and data. This helps to sanitize user input and protect against malicious queries.

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

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

// Bind parameter values to placeholders
$stmt->bindParam(':username', $username);

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

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

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