当我在WHERE子句中使用变量时,查询不起作用。我已经尝试了一切。我回显了变量$ res,它向我显示了一个理想值,当我在查询中使用该变量时,查询未获取任何内容,因此mysqli_num_rows给了我零值,但是当我给出了该变量静态包含查询的值时执行完美。我已经使用过相同类型的代码很多次,并且效果很好,但是现在在模块的这一部分中,它无法正常工作。
代码:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
答案 0 :(得分:0)
如评论中所述。通过打印查询var_dump($query)
,您将获得发送到数据库以进行查询的确切语法。
调试提示:您还可以通过在数据库中粘贴var_dump($ query)值进行测试,如果查询正常,就会看到结果。
因此,更新查询语法并打印查询将对您有所帮助。
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
希望这将对您和以后的新手有帮助,如何测试您的查询。
建议:另请参见如何编写mysql查询语法以更好地理解php variables inside mysql query
答案 1 :(得分:-1)
问题是您在查询中使用$res
的方式。请改用.$res
。在PHP(本机或框架)中,将变量注入查询需要正确的语法。