I am building a website for my college project and have decided to create the front page. On it i have tried to display the menu by representing the parent categories and by dynamically populating the categories with their subcategories retrieved by recursively calling a function which does the same by fetching data from the database. However, the result only shows the main or parent menus and does not show the sub categories. I am at a loss.
The php code is shown below.
<?php
session_start();
include("connection.php");
$a=0;
if(isset($_SESSION["valid_user"]))
{
echo "WELCOME ";
echo $_SESSION["valid_user"];
$name = $_SESSION["valid_user"];
$sqllist = "select * from category order by category_name";
$rscatlist = mysql_query($sqllist);
$catid1 = "";
$opt = "";
while($rowcatlist = mysql_fetch_array($rscatlist))
{
$catid1 = $rowcatlist["category_id"];
$catname = $rowcatlist["category_name"];
$opt .= "<option value='$catid1'>$catname</option>";
}
$sql1 = "select * from register where email_id='$name'" ;
$rs1 = mysql_query($sql1);
$row = 0;
$row1 = "";
while($row1=mysql_fetch_array($rs1))
{
$row = $row1["admin"];
}
if($row==1)
{
echo "                             <a href='admin/usermanagement/index.php'>Management Services </a>   ";
}
echo "<p align='right'><a href='logout.php'><font size='3'>logout</font></a></p>"."<br>" ."<br/>";
}
else
{
echo "<p align='right'><a href='register.php'><font size='3'>Register</font></a> or <a href='login.php'><font size='3'>Login</font></a></p>"."<br/>"."<br/>";
}
$tbl = "";
$cat_id = 0;
$tbl = recursive($tbl,$cat_id);
function recursive($tbl,$cat_id)
{
$sql = "select * from category where parent_id='$cat_id'";
$rs = mysql_query($sql);
$tbl.="<ul>";
while($row=mysql_fetch_array($rs))
{
$tbl .= "<li><a href='product.php?category_id=$row'[category_id]'>$row[category_name]</a>";
$sql1 = "select * from category where parent_id=$row'[category_id]'";
$rs1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($rs1))
{
recursive($tbl,$row["category_id"]);
}
$tbl.="</li>";
}
$tbl.="</ul>";
return $tbl;
}
?>
It seems odd that you’re calling the recursive() function right before you’re defining that function. It also seems odd that you’re only calling that function for the $cat_id of 0. Wouldn’t you need to loop through all your main-level category IDs and pass them into the function too?
And good Lord, has anyone ever taught you to comment your code 😉