How can PHP beginners efficiently generate menu items from database tables?
To efficiently generate menu items from database tables in PHP, beginners can use a loop to fetch the menu items from the database and dynamically create the menu structure. By querying the database for the menu items and looping through the results, beginners can generate the menu items dynamically without hardcoding each item.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Query to fetch menu items from database table
$stmt = $pdo->query("SELECT * FROM menu_items");
// Loop through the results and generate menu items
echo '<ul>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<li><a href="' . $row['url'] . '">' . $row['title'] . '</a></li>';
}
echo '</ul>';
?>