开发者

nav bar using sql and php

开发者 https://www.devze.com 2023-03-24 12:11 出处:网络
hi have two database tables : category (contains category name) sub_cats (contains sub categories) im trying to show sub cats for each cat

hi have two database tables :

category (contains category name) sub_cats (contains sub categories)

im trying to show sub cats for each cat i.e:

  • cat 1
    • sub cat
    • sub cat
    • sub cat
    • sub cat
  • cat 2
    • sub cat
    • sub cat
    • sub cat
    • sub cat

im using this query but its doesnt seems to work. what to do ?

$sql = mysql_query("SELECT category.dname AS dname, sub_cats.dname AS sdname
                   FROM category
   开发者_如何学JAVA                LEFT JOIN sub_cats
                   ON category.id = sub_cats.catid
                   ORDER BY category.id");

while ($row = mysql_fetch_array($sql)) {

    $cats .= '<li><a href="?'.$row['dname'].'">'.$row['dname'].'</a></li>
    <li> - - - <a href="?'.$row['sdname'].'">'.$row['sdname'].'</a></li>';
}


Try separating your queries

$sql = mysql_query("SELECT category.dname AS dname
                   FROM `category`
                   ORDER BY category.id");

while ($row = mysql_fetch_array($sql)) {

    $cats .= '<li><a href="?'.$row['dname'].'">'.$row['dname'].'</a></li>';

        $sql2 = mysql_query("SELECT sub_cats.dname AS sdname
                           FROM `sub_cats`
                           WHERE sub_cats.catid = " . $row['id']);

        while ($row2 = mysql_fetch_assoc($sql2)) {

            $cats .= '<li> - - - <a href="?'.$row['sdname'].'">'.$row['sdname'].'</a></li>';
        }
}


This is how you should do the printing with your current query:

$cats .= '<ul>';
$currentCat = null;
while ( $row = mysql_fetch_array($sql) ) {
    if( $row[ 'dname' ] !== $currentCat ) {
        if( $currentCat !== null ) $cats .= '</ul>';
        $currentCat = $row[ 'dname' ];
        $cats .= '<li><a href="?'.$row['dname'].'">'.$row['dname'].'</a></li>';
        $cats .= '<ul>';
    }
    $cats .= '<li><a href="?'.$row['sdname'].'">'.$row['sdname'].'</a></li>';
}
if( $currentCat !== null ) $cats .= '</ul>';
$cats .= '</ul>';
0

精彩评论

暂无评论...
验证码 换一张
取 消