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', 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);
?>
<ul>
<?php foreach ($menuItems as $item): ?>
<li>
<?php echo htmlspecialchars($item['name']); ?>
<?php if (!empty($item['children'])): ?>
<ul>
<?php foreach ($item['children'] as $child): ?>
<li><?php echo htmlspecialchars($child['name']); ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>