我有一个表单,它使用html表单从用户那里获取一个值(id),并在名为"account"的数据库中查找它以显示所有值。如果用户输入的值在数据库中不存在,则应显示警报。
//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()
也将返回true。您希望使用mysql_num_rows
来检查是否返回了任何行。
此外,您应该真正开始使用PDO或mysqli进行数据库查询。它的安全性要高得多——不像mysql_函数那样受到抨击。
http://us2.php.net/manual/en/ref.pdo-mysql.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")) ) {
if(mysql_num_rows($result)) {
// Rows Returned
}else{
echo '<script type="text/javascript">alert("Id not found in database!");</script>';
}
} else {
// Mysql Error (Error with Query)
}
mysql_close($con);
?>
对于SELECT、SHOW、DESCRIBE、EXPLAIN和其他返回resultset,mysql_query()在成功时返回资源,在失败时返回FALSE错误
SQL语句、INSERT、UPDATE、DELETE、DROP等,mysql_query()成功时返回TRUE,错误时返回FALSE。
要检查是否有返回的行,您需要使用
mysql_num_rows()
您正在使用不推荐使用的mysql_函数。
您应该用准备好的语句启动mysqli_ or PDO
。
if( ($result=mysql_query("select * from my_table where id=$name")) )
应该是
if( ($result==mysql_query("select * from my_table where id=$name")) )