1
votes

I ran into this problem earlier but I didn't ask it because I found a work around, however Im not so lucky this time.

I am trying to create a simple list for each "pg.pcat" (page category) to show 5 latest links from each category (I am aware I didn't add LIMIT or ORDER BY).

$q2 = "
SELECT pg.pcat, p.page_id, p.link_title 
FROM pages AS P 
INNER JOIN page_categories AS pg ON pg.pc_id = $sidenav
";

$r2 = @mysqli_query ($dbc, $q2); // Run the Query.  

while ($qarr = mysqli_fetch_array($r2, MYSQLI_ASSOC)) {
    if(!isset($printed)) { 
        echo "<div class=\"sideNavSpan\">{$qarr['pcat']}</div>";
        $printed = true;
    }
    echo "
    <li>
     <a href=\"page.php?pid={$qarr['page_id']}\">{$qarr['link_title']}</a>
    </li>
    ";
}

I need something like this but I can't figure out how to use a for loop on the values in $qarr.

----pg.pcat1
p.link_title
p.link_title
p.link_title
p.link_title
p.link_title

----pg.pcat2
p.link_title
p.link_title
p.link_title
p.link_title
p.link_title

----pg.pcat3
p.link_title
p.link_title
p.link_title
p.link_title
p.link_title

etc. help? please and thank you :)

1
FYI - You're missing the closing </li> tag. Also aren't you going to wrap your list items in a list like `<ul>'? - Naveed Ahmad
@Naveed - In HTML AFAIK you do not need the closing tag for LI's. In XHTML you do, but not in HTML. Although it is a good practice to do so (I added it in my edit before you mentioned it, btw). - Jared Farrish

1 Answers

1
votes

You'll need to order by pg.pcat in your SQL query, and wrap the whole of this in an if test to ensure that at least one row has been returned

$currCat = '';
$printed = false;
while ($qarr = mysqli_fetch_array($r2, MYSQLI_ASSOC)) {     
   if($currCat != $qarr['pcat']) {  // category has changed
      if ($printed) { // we already printed an opening <ul> so we need to close it
         echo '</ul>';
         $printed = true;
      }
      echo"<div class=\"sideNavSpan\">{$qarr['pcat']}</div><ul>";
      $currCat = $qarr['pcat'];
   }
   echo "<li><a href=\"page.php?pid={$qarr['page_id']}\">{$qarr['link_title']}</a></li>";
}
echo '</ul>';