nesting mySQL queries/while statements

From: Date: Sat, 06 Jan 2001 04:05:48 +0000
Subject: nesting mySQL queries/while statements
Groups: php.general 
Request: Send a blank email to php-general+get-33007@lists.php.net to get a copy of this message
Hello, I may not be explaining what I'm trying to do correctly; I'm coming from an extensive WebCatalog background, which uses a rather different vocabulary. I'm working on a test site to train myself in PHP/mySQL. I have a lot of sample data, organized into categories ("flavors"). While each table row is unique, there are instances where data is duplicated. Here's an example:
firstname  lastname  flavor    content
John       Smith     Address   1234 Test Street, Provo, UT 12345
John       Smith     Work      Widget Tightener for Amalgamated Megacorp
John       Smith     Work      Pawn shop janitor
Harry      Jones     Work      Supervisor
Harry      Jones     Work      PHP Programmer
That kind of thing. I can get results out of the table and display a long list of them just fine. I can use DISTINCT in the query to list only last names. What I want to do, however, is nest the results, like this: Jones Harry Jones, PHP Programmer Harry Jones, Supervisor Smith John Smith, Pawn shop janitor John Smith, Widget Tightener for Amalgamated Megacorp This code snippet works just fine for the simple list: ------------- $result = mysql_query("SELECT DISTINCT lastname FROM content WHERE flavor=$flavorsku",$db);
    while ($myrow = mysql_fetch_array($result)) {
        printf ("<b>%s</b><br> \n", $myrow["lastname"]);
    }
-------------- But I'm obviously doing something screwy when I try to search again on each unique instance of lastname. This is the result I get: "Warning: 0 is not a MySQL result index in /path/page.html on line 89." (Which is the line where I have the second "while") Here's the code that's breaking: ------------- $result = mysql_query("SELECT DISTINCT lastname FROM content WHERE flavor=$flavorsku",$db);
    while ($myrow = mysql_fetch_array($result)) {
        printf ("<b>%s</b><br> \n<ul>", $myrow["lastname"]);
        $lastname = ($myrow["lastname"]);
        $result = mysql_query("SELECT * FROM content WHERE lastname=$lastname",$db);
        while ($myrow = mysql_fetch_array($result)) {
printf("<a href=\"%s?sku=%s\">%s %s: %s</a><br> \n", $PHP_SELF, $mysubrow["sku"], $mysubrow["firstname"], $mysubrow["lastname"], $mysubrow["title"]); } -------------- The nested while doesn't look right to me, but I don't know what the alternative would be. Obviously there are better ways to do this. Thanks for any light anyone can shed on this. -- Maurice Rickard http://mauricerickard.com/

« previous php.general (#33007) next »