2

I'm having trouble trying to get a nested < ul > inside of a while loop. I'm not sure if this even possible so i'm open to alternatives.

Here's a quick image of what my database looks like and what i'm trying to achieve.

Here's my sql

SELECT * 
FROM drinks_category, drinks_lookup, drinks 
WHERE drinks.drink_id = drinks_lookup.drink_id 
AND drinks_lookup.drinks_category_id = drinks_category.drinks_category_id
ORDER BY drinks_category.drinks_category_title

Here's my output php

$result = $conn->query($sql) or die(mysqli_error());

$last_category = 0;

while ($row = $result->fetch_assoc()) {

    if($row['drinks_category_id'] != $last_category) {
     echo "<h1>" . $row['drinks_category_title'] . "</h1>";
    }

    echo "<p>" . $row['drink_name'] . "</p>";
    $last_category = $row['drinks_category_id'];

}

Im using mysqli and php. Thanks in advance!

4

3 回答 3

1

Update your while loop to the following:

while ($row = $result->fetch_assoc()) {

if($row['drinks_category_id'] != $last_category) {
 if($last_category != 0) echo '</ul>';
 echo "<h1>" . $row['drinks_category_title'] . "</h1>";
 echo "<ul>";
}

echo "<li>" . $row['drink_name'] . "</li>";
$last_category = $row['drinks_category_id'];

}
if($last_category != 0) echo "</ul>";
于 2013-05-26T00:30:20.237 回答
0

Instead of having 3 tables, you could just add a category_id to your drinks table, just to simplify things. Then you can do this:

SELECT drink_name, (SELECT drnk_category_title FROM drinks_category WHERE drink_category_id = drink_category // THE COLUMN I SUGGESTED //) AS title FROM drinks

And then you can loop the result and build the nodes you desire really easily

于 2013-05-26T00:35:00.560 回答
0
$result = $conn->query($sql) or die(mysqli_error());

$last_category = 0;

while ($row = $result->fetch_assoc()) {

    if($row['drinks_category_id'] != $last_category) {
        // close previous </ul>
        if( $last_category != 0 ) echo "</ul>";

        // new title
        echo "<h1>" . $row['drinks_category_title'] . "</h1>";

        // new <ul>
        echo "<ul>";

        $last_category = $row['drinks_category_id'];
    }

    echo "<li>" . $row['drink_name'] . "</li>";
}

// close last </ul>
if( $last_category != 0 ) echo "</ul>";
于 2013-05-26T00:37:04.570 回答