我有一个表单,它使用html表单从用户处获取值(id),并在名为“account”的数据库中查找以显示所有值。如果用户输入的值在数据库中不存在,则应显示警报。即使设置为空时,php mysql查询也会返回true
//user_form.html
<html>
<form method="get" action="user_action.php">
<input type="text" name="val"/>
<input type="submit" value="Enter"/>
</form>
</html>
//user_action.php
<?php
$name=$_GET["val"];
$con = mysql_connect("localhost","my_username","my_password") or die('Could not connect: ' . mysql_error());
mysql_select_db("account",$con);
if(($result=mysql_query("select * from my_table where id=$name")))
//display the database table
else
echo '<script type="text/javascript">alert("Id not found in database!");</script>';
mysql_close($con);
?>
我的问题是,当我输入ID不存在于数据库中的值,它不会进入else块,并显示警报。 那么,为什么查询对所有值都返回true?
由于双括号,他所做的方式是正确的,以检查mysql_query是否为false。因为他正在设置结果变量,所以不需要双等号。 – David
即使没有双重修辞,它也是有效的。单等于变量将'mysql_query'的返回值赋值给$ result,并将其返回 - 因此,您将结果分配给$ result,并同时测试$ result是否为“true”。 ==比较从'mysql_query'到'$ result'的值的返回值 - 由于我怀疑$ result被定义,所以它可能是所需要的对象。 – Adam