Dividing query results and displaying

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Wilbo
Forum Newbie
Posts: 22
Joined: Fri Jul 25, 2008 5:45 am

Dividing query results and displaying

Post 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
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Dividing query results and displaying

Post 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 />';
}
(#10850)
User avatar
Frozenlight777
Forum Commoner
Posts: 75
Joined: Wed May 28, 2008 12:59 pm

Re: Dividing query results and displaying

Post 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
Post Reply