在网页侧栏上显示类别列表

时间:2011-07-31 07:15:52

标签: php mysql categories cart shopping

PHP新手在这里。我目前正在使用PHP开发一个购物车网站,我的问题是如何在我的边栏上制作动态类别树列表?因为我不知道如何实现它。我已经完成了在数据库中添加类别。

1 个答案:

答案 0 :(得分:1)

根据您提供的有关您需要多少级别类别的有限信息,以下是一个可能有帮助的示例?

    // 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();

根据侧栏的要求,在您的css文件中设置您的L1类别和L2类别的样式,并且您应该在路上,这些链接需要更改以适合您的网站,他们就是一个例子