I’m building a simple web app at the moment that I’ll one day open source. As it stands at the moment, the nav is generated on every page load (which will change to be cached one day) but for the moment, it’s being made with the code below. Using PHP 5.2.6 and MySQLi 5.0.7.7, how more efficient can the code below be? I think joins might help, but I’m after advice. Any tips would be greatly appreciated.
<?php
$navQuery = $mysqli->query("SELECT id,slug,name FROM categories WHERE live=1 ORDER BY name ASC") or die(mysqli_error($mysqli));
while($nav = $navQuery->fetch_object()) {
echo '<li>';
echo '<a href="/'. $nav->slug .'">'. $nav->name .'</a>';
echo '<ul>';
$subNavQuery = $mysqli->query("SELECT id,name FROM snippets WHERE category='$nav->id' ORDER BY name ASC") or die(mysqli_error($mysqli));
while($subNav = $subNavQuery->fetch_object()) {
echo '<li>';
echo '<a href="/'. $nav->slug .'/'. $subNav->name .'">'. $subNav->name .'</a>';
echo '</li>';
}
echo '</ul>';
echo '</li>';
}
?>
You can run this query:
Then iterate thru the results to create the proper heading like:
Note that I used
printfbut you should use your own function instead which wraps around printf, but runshtmlspecialcharsthru the parameters (except the first of course).Disclaimer: I do not necessarily encourage such use of
<ul>s.This code is just here to show the basic idea of processing hierarchical data got with one query.