How can PHP be used to dynamically generate HTML pages based on data stored in a database?

To dynamically generate HTML pages based on data stored in a database using PHP, you can retrieve the data from the database using SQL queries, loop through the results, and output them as HTML elements on the page. This allows for creating dynamic and data-driven web pages that can be updated easily by modifying the database records.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Prepare and execute a SQL query to retrieve data from the database
$stmt = $pdo->query('SELECT * FROM your_table');
$results = $stmt->fetchAll();

// Loop through the results and output them as HTML elements
foreach ($results as $row) {
    echo '<div>';
    echo '<h2>' . $row['title'] . '</h2>';
    echo '<p>' . $row['content'] . '</p>';
    echo '</div>';
}
?>