0

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?

1 Answer 1

1

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

$query = "SELECT p.*,c.* FROM Products p,City c";
Sign up to request clarification or add additional context in comments.

1 Comment

Very quick clean solution. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.