user3181236
user3181236

Reputation: 357

Do - While loops in PHP

I have what is probably a ridiculously simple problem to solve in PHP, but my brain will not engage.

I have products divided into categories. I have performed a successful query which gives me an array containing the products joined to their respective categories. Now I want to display them by category, splitting each category up into its own div. I have the following code:

$current_category = 0;

do
    {

        if($current_category != $row['category_id']){

            echo '<div class="block">
                    <div class="menu">
                        <h4>'.$row['category_name'].'</h4>
                        <ul>';

            do
            {
                echo '<li><a>'.$row['product_name'].'</a></li>';

            }
            while ($row['category_id'] == $current_category);

            $current_category++;

            //close list and divs
            echo '</ul>
                </div>
                </div>';
        }

    }
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC));

But this only outputs the first product in each category, rather than outputting them all then moving on to the next. What am I doing wrong?

Upvotes: 1

Views: 70

Answers (1)

Eric
Eric

Reputation: 97591

You need to get the next row in the inner loop, not in the outer one:

do {
    // no need to check we're in the right category - we always are
    $current_category = $row['category_id'];


    echo '<div class="block">
              <div class="menu">
                   <h4>'.$row['category_name'].'</h4>
                   <ul>';

    do {
        echo '<li><a>'.$row['product_name'].'</a></li>';

        // !!! get the next row here
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    while ($row['category_id'] == $current_category);

    //close list and divs
    echo '</ul>
          </div>
          </div>';

// !!! and don't get it again here
} while ($row);

You need to make sure that your SQL query sorts by category first

Upvotes: 1

Related Questions