Wyatt Jackson
Wyatt Jackson

Reputation: 303

Nested mysql while loop not returning expected results

I have 2 tables, and I'm trying to use a nested while loop to list all possibilities. Unfortunately, I'm only getting a small subset of results. Any help is much appreciated.

Products Table

Product_ID | Product_Name | Product_Desc
0          | Box          | Big Box     
1          | Toy          | Nice Toy  

City Table

City_ID    | City_Name 
0          | Cincinnati    
1          | Detroit
2          | San Francisco
3          | San Diego
4          | New York

Expected desired results:

0 Box Big Box 0 Cincinnati
0 Box Big Box 1 Detroit
0 Box Big Box 2 San Francisco
0 Box Big Box 3 San Deigo
0 Box Big Box 4 New York
1 Toy Nice Toy 0 Cincinnati
1 Toy Nice Toy 1 Detroit
1 Toy Nice Toy 2 San Francisco
1 Toy Nice Toy 3 San Diego
1 Toy Nice Toy 4 New York

My Incorrect Results:

0 Box Big Box 0 Cincinnati
1 Toy Nice Toy 0 Cincinnati

Here is my code:

query = "SELECT * FROM Products";
$result = mysqli_query($con, $query);

$query2 = "SELECT * FROM Cities";
$result2 = mysqli_query($con, $query2);


while($row = mysqli_fetch_assoc($result))
    {
         $product_id = $row['Product_ID'];
         $product_name = $row['Product_Name'];
         $product_desc = $row['Product_Desc'];

        while($row = mysqli_fetch_assoc($result2))
        {
        $city_id = $row['City_ID'];
        $city_name = $row['City_Name'];
        }

    echo "$product_id $product_name $product_desc $city_id $city_name\n";

}

Unfortunately, the above is not working and I'm only getting this result. Should I be using a foreach product instead?

Upvotes: 0

Views: 44

Answers (1)

Jeffry Evan
Jeffry Evan

Reputation: 327

actually you can get the same result with single query without using nested loop

$query = "SELECT p.*,c.* FROM Products p,City c";

Upvotes: 1

Related Questions