Page 1 of 1

Dividing query results and displaying

Posted: Fri Jul 25, 2008 5:52 am
by Wilbo
Hi there,
I've got a links page that lists all of the links in one big long list using a while loop:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

echo '
<p><a href="'.$row['link_url'].'">' . $row['link_name'] .'</a></p>
<p>'.$row['link_description'].'</p><br />';
}
thats fine but I want to change it so that the links are divided up into categories.
At the moment I've done it the stupid way by having a seperate SELECT query for each category and then running the above code for each query.
Could someone tell me a better way?

What I want to end up with is a links page which has a title for each category followed by the links related to that cateogry. Pretty simple stuff.

Thanks in advance,

Wilbo

Re: Dividing query results and displaying

Posted: Fri Jul 25, 2008 11:33 am
by Christopher

Code: Select all

// add "ORDER BY category,name" to sort by category first to your SQL
// the logic for category headings is usually like this
$category = '';    // initialize to no value so it will display the first heading
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    // check if category has changed
    if ($category != $row['category']) {
        echo '<h1>'.$row['category'].'</h1>';
        $category = $row['category'];      // set $category to new category
    }
    echo '<p><a href="'.$row['link_url'].'">' . $row['link_name'] .'</a></p>
        <p>'.$row['link_description'].'</p><br />';
}

Re: Dividing query results and displaying

Posted: Fri Jul 25, 2008 11:35 am
by Frozenlight777
adjust your database so you have a category field. Then adjust your select queries to something like

select * from links where category = '$category'; or something like that

then do what yo u were doing before with the loops.. you're going to need to do one for each category from what it looks like