我有2个表,我试图使用嵌套的while循环列出所有可能性。不幸的是,我只获得了一小部分结果。任何帮助深表感谢。
产品表
Product_ID | Product_Name | Product_Desc
0 | Box | Big Box
1 | Toy | Nice Toy
城市表
City_ID | City_Name
0 | Cincinnati
1 | Detroit
2 | San Francisco
3 | San Diego
4 | New York
预期的预期结果:
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
我的错误结果:
0 Box Big Box 0 Cincinnati
1 Toy Nice Toy 0 Cincinnati
这是我的代码:
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";
}
不幸的是,上述情况不起作用,我只是得到了这个结果。我应该使用foreach产品吗?
答案 0 :(得分:1)
实际上,您可以使用单个查询获得相同的结果,而无需使用嵌套循环
$query = "SELECT p.*,c.* FROM Products p,City c";