Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active June 5, 2023 12:19
Show Gist options
  • Save code-boxx/253be7a1fd9b903b9dd4c72b61e98fcf to your computer and use it in GitHub Desktop.
Save code-boxx/253be7a1fd9b903b9dd4c72b61e98fcf to your computer and use it in GitHub Desktop.
PHP MYSQL Dynamic Menu

DYNAMIC MENU WITH PHP MYSQL

https://code-boxx.com/dynamic-navigation-menu-php-mysql/

NOTES

  1. Create a database and import 1-menu.sql.
  2. Change the database settings in 2-menu.php to your own.
  3. Launch 3a-demo.php in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `menu_items` (
`item_id` bigint(20) NOT NULL,
`parent_id` bigint(20) NOT NULL DEFAULT 0,
`item_text` varchar(255) NOT NULL,
`item_link` varchar(255) NOT NULL,
`item_target` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `menu_items`
ADD PRIMARY KEY (`item_id`),
ADD KEY (`parent_id`);
ALTER TABLE `menu_items`
MODIFY `item_id` bigint(20) NOT NULL AUTO_INCREMENT;
INSERT INTO `menu_items` (`item_id`, `parent_id`, `item_text`, `item_link`, `item_target`) VALUES
(1, 0, 'Home', '/', NULL),
(2, 0, 'Blog', 'blog/', NULL),
(3, 0, 'Reviews', 'reviews/', NULL),
(4, 0, 'Shop', 'shop/', '_BLANK'),
(5, 2, 'How To', 'blog/how/', NULL),
(6, 2, 'Technology', 'blog/tech/', NULL),
(7, 2, 'Hacks', 'blog/hacks/', NULL);
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbHost = "localhost";
$dbName = "test";
$dbChar = "utf8mb4";
$dbUser = "root";
$dbPass = "";
$pdo = new PDO(
"mysql:host=$dbHost;dbname=$dbName;charset=$dbChar",
$dbUser, $dbPass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
// (B) DRILL DOWN GET MENU ITEMS
// ARRANGE BY [PARENT ID] => [MENU ITEMS]
$menu = []; $next = [0];
while (true) {
$stmt = $pdo->prepare(sprintf(
"SELECT * FROM `menu_items` WHERE `parent_id` IN (%s)",
implode(",", $next)
));
$stmt->execute();
$next = [];
while ($r = $stmt->fetch()) {
if (!isset($menu[$r["parent_id"]])) { $menu[$r["parent_id"]] = []; }
$menu[$r["parent_id"]][$r["item_id"]] = $r;
$next[] = $r["item_id"];
}
if (count($next) == 0) { break; }
}
// (C) CLOSE DATABASE CONNECTION
$stmt = null;
$pdo = null;
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Menu Demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="3b-demo.css">
</head>
<body>
<nav class="menu"><?php
// (A) SUPPORT FUNCTION TO DRAW AN <A>
function draw ($i) {
printf("<a %shref='%s'>%s</a>",
$i["item_target"]!="" ? "target='". $i["item_target"] ."' " : "" ,
$i["item_link"], $i["item_text"]
);
}
// (B) DRAW MENU ITEMS
require "2-menu.php";
foreach ($menu[0] as $id=>$i) {
// (B1) WITH SUB-ITEMS
if (isset($menu[$id])) { ?>
<div class="mGrp">
<div class="mTitle"><?=$i["item_text"]?></div>
<div class="mItems"><?php
foreach ($menu[$id] as $cid=>$c) { draw($c); }
?></div>
</div>
<?php
// (B2) SINGLE MENU ITEM
} else { draw($i); }
}
?></nav>
</body>
</html>
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
/* (B) FIRST LEVEL */
.menu {
display: flex;
background: #161616;
}
.menu a, .mGrp {
position: relative;
color: #fff;
padding: 15px;
display: block;
width: 100%;
text-decoration: none;
}
.menu a:hover, .mGrp:hover {
cursor: pointer;
background: #5f0c08;
}
/* (C) SECOND LEVEL DROP-DOWN */
/* (C1) DROP-DOWN ITEMS */
.mItems {
width: 100%;
background: #333;
position: absolute;
top: 100%; left: 0;
display: none;
}
.mGrp:hover .mItems { display: block; }
.mItems a:hover { background: #8c1f1f; }
/* (C2) ADD ICON */
.mGrp::after {
content: "\25BA";
position: absolute;
top: 15px;
right: 10px;
transition: transform 0.3s;
}
.mGrp:hover::after { transform: rotate(90deg); }
/* (D) RESPONSIVE - SINGLE COLUMN ON SMALL SCREEN */
@media screen and (max-width: 640px) {
.menu { flex-wrap: wrap; }
.menu a, .mGrp {
border-bottom: 1px solid #262626;
}
.mItems {
margin-top: 10px;
position: static;
}
}
<?php
// (A) GET MENU ITEMS
require "2-menu.php";
// (B) SUPPORT FUNCTION TO DRAW AN <A>
function draw ($i) {
printf("<a %shref='%s'>%s</a>",
$i["item_target"]!="" ? "target='". $i["item_target"] ."' " : "" ,
$i["item_link"], $i["item_text"]
);
}
// (C) WRITE HTML MENU TO FILE
ob_start();
foreach ($menu[0] as $id=>$i) {
// (C1) WITH SUB-ITEMS
if (isset($menu[$id])) { ?>
<div class="mGrp">
<div class="mTitle"><?=$i["item_text"]?></div>
<div class="mItems"><?php
foreach ($menu[$id] as $cid=>$c) { draw($c); }
?></div>
</div>
<?php
// (C2) SINGLE MENU ITEM
} else { draw($i); }
}
// (C3) OB TO MENU.HTML
file_put_contents("menu.html", str_replace(["\r", "\n"], "", ob_get_contents()));
ob_end_flush();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment