如何在SQL查询中使用带有表对象的$ result变量使用mySQLi

时间:2016-05-01 15:25:16

标签: php html mysql sql mysqli

我正在努力使这段代码工作,但它只能在第二个echo语句echo "Finished 2";之前有效。

<?php
if (count($_GET) > 0){
$sql = "SELECT * FROM winery WHERE winery_name='".$_GET['winery_name']."'";
echo "Finished 1";
$result = $db->query($sql);
echo "Finished 2";
$sql = "SELECT * FROM".$result."WHERE wine_type='".$_GET['wine_type']."'";
echo "Finished 3";
$result = $db->query($sql);
echo "Finished 4";
$sql = "SELECT * FROM".$result.", wine_variety WHERE wine_id=wine_variety.wine_id";
echo "Finished 5";
$result = $db->query($sql);
echo "Finished 6";
$sql = "SELECT * FROM".$result."WHERE variety_id='".$_GET['grape_variety']."'";
echo "Finished 7";
$result = $db->query($sql);
echo "Finished all queries";

}
?>

根据我的理解,问题是sql不会将$result识别为表,但$result存储来自查询的返回表。如何让SQL在新查询中使用$result的返回表?

enter image description here

1 个答案:

答案 0 :(得分:1)

我想从您的酒庄表中获取其他表名???

如果需要,您需要从$ result中获取行,然后从winery表中获取相应的列(即具有其他表名的列)。

BTW最佳选择是加入两张桌子。

我认为你犯错的另一点是

$sql = "SELECT * FROM".$result."WHERE wine_type='".$_GET['wine_type']."'";

应该是

$sql = "SELECT * FROM ".$result." WHERE wine_type='".$_GET['wine_type']."'";
FROM&amp;之间的空间双引号和双引号和WHERE之间

要从winary_name获取winery_id,您可以编写HTML表单,如

<select name="winary_id">
    <option value="Winary ID HERE">Winary Name Here</option> // you can generate your dynamic options like this which will return id instead of name
</select>