Page 1 of 1

displaying data pulled from db ???

Posted: Fri Feb 11, 2005 7:57 pm
by decoy1
I wrote the function below to query the db to select all categories and their respective links then spit them out. The problem I'm having is figuring out a way to tell when a category is 'out of links' and it moves on to the next category.

As you can see I wrap everything in a table and when a category has no more links to display and when it moves on to the next category (and a new table cell) it's missing the '</td>' tag.

Code: Select all

function catsWithLinks()
&#123;
  $query = "select lc.catid, lc.cat_name, l.name, l.link_url from link_cat as lc, links as l
  where l.catid = lc.catid order by lc.cat_name asc, l.name asc"; 
  $result = @mysql_query($query);
 
  $cat='';
 
  $cats = '<table border=0 cellpadding=2 cellspacing=12><tr>';
  while($row = mysql_fetch_array($result))
  &#123;
    if($row&#1111;"cat_name"] != $cat)    
    &#123;
      $cat = $row&#1111;"cat_name"];
      $id = $row&#1111;"catid"];
      $cats .= '<td valign=top class=mediumbold>' .strtoupper($cat). '';            
    &#125;
    $link = $row&#1111;"name"];
    $address = $row&#1111;"link_url"]; 
    $cats .= '<br><a href=' .$address. '>' .$link. '</a>';    
  &#125;
  $cats .= '</td></tr></table>';
  return $cats;
&#125;
Am I going to have to use another query somehow or could I do something like

Code: Select all

if(no more links for this category)&#123;
  $cats .= '<br><a href=' .$address. '>' .$link. '</a></td>';  
&#125;
else&#123;
  $cats .= '<br><a href=' .$address. '>' .$link. '</a>'; 
&#125;
Thanks

Posted: Fri Feb 11, 2005 8:01 pm
by feyd
typically we would track which category we are in, and output the '</td><td>' based on when the category changes. After all links are output, the cell is closed along with the rows and such..

Posted: Fri Feb 11, 2005 8:51 pm
by decoy1
Hey feyd... How would I tell when the category changes? Could you give me a brief example with my existing code or do I have to have another query in there somewhere?

Thanks

Posted: Fri Feb 11, 2005 8:58 pm
by feyd
it doesn't need a seperate query. Create a variable where you can keep the previous category. Compare that category against the current one, if they differ, print the table cell stuff. Remember that the first category shouldn't have the table cell ending stuff ;)

Posted: Fri Feb 11, 2005 9:04 pm
by decoy1
Just how I like it... simple and effective. Thanks feyd!