PHP newbie here. I'm currently developi开发者_开发技巧ng a shopping cart web site using PHP and my question is how do I make a dynamic category tree listing on my side bar? Because I have no idea on how to implement it. I'm done with adding of categories in database.
With the limited information you provided on how many levels of categories you require, here is an example that may help?
// create a function to get the categories
function getCategories() {
// query the top level categories
$query = "SELECT catId,catName FROM categories ORDER BY catName";
$result = mysql_query($query);
// check that you got some results before proceeding
if (mysql_num_rows($result)>0) {
// create a $html variable to return from the function
$html = '<ul class="L1-categories">';
// loop through the results
while ($rows = mysql_fetch_object($result)) {
// append top level cats to your $html variable
$html .= '<li><a href="index.php?category='.$rows->catId.'">'.$rows->catName.'</a>';
// repeat the above query for 2nd level categories (sub cats)
$queryL2 = "SELECT subId,subName FROM subCategories WHERE catId=".$rows->catId." ORDER BY subName";
$resultL2 = mysql_query($queryL2);
// check you got results
if (mysql_num_rows($resultL2)>0) {
// continue appending the variable with some html that show sub cats indented
$html .= '<ul class="L2-categories">';
// loop through the sub cats
while ($rowsL2 = mysql_fetch_object($resultL2)) {
// if there were sub sub cats etc you just keep this code going deeper
$html .= '<li><a href="index.php?category='.$rows->catId.'&sub='.$rowsL2->subId.'">'.$rowsL2->subName.'</a></li>';
} // end sub cats loop
$html .= '</ul>';
} // end check for results
$html .= '</li>';
} // end top level cats loop
$html .= '</ul>';
}
return $html;
}
// usage
echo getCategories();
Style up your L1-categories and L2-categories in your css file as required for your side bar and you should be on your way, those links will need to change to suit your website they are just there for an example
精彩评论