开发者

PHP Category Menu (mySQL)

开发者 https://www.devze.com 2023-02-13 09:08 出处:网络
This is probably an easy fix - but I\'ve been getting A LOT of issues trying to set this up. Basically I\'m trying to create a category menu for an article page. The \"list\" has each category and und

This is probably an easy fix - but I've been getting A LOT of issues trying to set this up. Basically I'm trying to create a category menu for an article page. The "list" has each category and underneath that list would be each article with the same attribute.

I have two tables set up one that holds all the categories and the o开发者_如何学JAVAther which holds the news posts. Yet for some reason...only the first post shows up - not the latter...

For example:

African Animals

Lion

Elephant

Farm Animals

Pig

<?php
    $STH = $DBH->query('SELECT * FROM articles_category');
        while($row = $STH->fetch()) { 
            echo "<li>\n";
            echo "<a href='' class='nav-top-item'>". $row['category'] ."</a>\n";
            echo "<ul>\n";
            $STH = $DBH->query('SELECT * FROM articles WHERE category="'. $row['category'] .'"');
                    while($row = $STH->fetch()) { 
                        echo "<li><a href='articles/article?id=". $row['id'] ."'>". $row['title'] ."</a></li>\n";
                    }
            echo "</ul>\n";
            echo "</li>\n";
            }   
?> 


$STH_2 = $DBH->query('SELECT * FROM articles ...'
while($row_2 = $STH_2->fetch()) {
   echo "<li><a href='articles/article?id=". $row_2['id'] ."'>". $row_2['title'] ."</a></li>\n";
} 

You are loading subcategory to same array $STH, change name, and second while should have different name too -> $row_2 will help


You are overwriting the $STH variable in the inner loop.

Change:

$STH = $DBH->query('SELECT * FROM articles WHERE category ...

To:

$STH2 = ...
    while($row = $STH2->fetch()) {  


You may not use the same identifier for two operations which shall be different (which is happening in your case with $STH. Because of doing that, you are overwritting $STH in the inner scope and that propagates to the outside loop condition.

You should change the variable name and you should also consider changing it to a more descriptive name : )

0

精彩评论

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

关注公众号