简体   繁体   English

嵌套mysql while循环未返回预期结果

[英]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. 我有2个表,并且尝试使用嵌套的while循环列出所有可能性。 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? 我应该改用foreach产品吗?

实际上,您可以使用单个查询获得相同的结果,而无需使用嵌套循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM