What security considerations should be taken into account when dynamically generating HTML content from database queries in PHP?

When dynamically generating HTML content from database queries in PHP, it is crucial to sanitize and validate the input data to prevent SQL injection attacks and cross-site scripting (XSS) vulnerabilities. This can be done by using prepared statements with parameterized queries and escaping user input before outputting it to the HTML.

// Example of using prepared statements to dynamically generate HTML content from database queries

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

// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_GET['username']);

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

// Fetch the results and output them safely to the HTML
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<div>' . htmlspecialchars($row['username']) . '</div>';
}