Jump to content

How to create a menu list from mysql data


etrader

Recommended Posts

use a multi-dimensional array... i.e. $menu[1]['name']='Finance'; $menu[1][x]='Item';

 

$sql=@mysql_query("SELECT * FROM tableName ORDER BY IFNULL(parent_id,0)");

$menu=array();
while ($row=mysql_fetch_assoc($sql)) {
if (is_null($row['parent_id'])) {
$menu[$row['id']]['name']=$row['menu_name'];
} else {
$menu[$row['parent_id'][]=$row['menu_name'];
}

foreach ($menu AS $m) {
echo "<ul><li>{$m['name']}";

if (is_array($m) {
echo "<ul>";
foreach ($m AS $m2) {
echo "<li>$m2</li>";
}
echo "</ul>";
}
echo "</li></ul>";
}

 

html may be wrong but you get the idea...

Just 1 improvement to what joel24 posted. Rather than suppressing a potential error, check whether there is records or not.

$sql=mysql_query("SELECT * FROM tableName ORDER BY IFNULL(parent_id,0)");

if(mysql_num_rows($sql) > 0)
{

$menu=array();
while ($row=mysql_fetch_assoc($sql)) {
if (is_null($row['parent_id'])) {
$menu[$row['id']]['name']=$row['menu_name'];
} else {
$menu[$row['parent_id'][]=$row['menu_name'];
}

foreach ($menu AS $m) {
echo "<ul><li>{$m['name']}";

if (is_array($m) {
echo "<ul>";
foreach ($m AS $m2) {
echo "<li>$m2</li>";
}
echo "</ul>";
}
echo "</li></ul>";
}

} else {
  echo "There is no records!";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.