Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
CREATE TABLE menu_items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
parent_id INT DEFAULT NULL
);
INSERT INTO menu_items (name, parent_id) VALUES
('Home', NULL),
('About', NULL),
('Services', NULL),
('Web Development', 3),
('SEO', 3),
('Frontend', 4),
('Backend', 4),
('Contact', NULL);
Select * from menu_items;
<?php
function getMenuItems($pdo, $parent_id = NULL) {
$sql = "SELECT * FROM menu_items WHERE parent_id " . ($parent_id ? "= :parent_id" : "IS NULL");
$stmt = $pdo->prepare($sql);
if ($parent_id) {
$stmt->bindParam(':parent_id', $parent_id, PDO::PARAM_INT);
}
$stmt->execute();
$menu = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['children'] = getMenuItems($pdo, $row['id']);
$menu[] = $row;
}
return $menu;
}
$menuItems = getMenuItems($pdo);
function renderMenu($items) {
echo '<ul>';
foreach ($items as $item) {
echo '<li>' . htmlspecialchars($item['name']);
if (!empty($item['children'])) {
renderMenu($item['children']);
}
echo '</li>';
}
echo '</ul>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Menu</title>
<style>
ul {
list-style-type: none;
}
li {
margin: 5px 0;
}
</style>
</head>
<body>
<?php renderMenu($menuItems); ?>
</body>
</html>