2014-04-19 83 views
-1

我有一个表单,它使用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?

回答

1

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); 
?> 
-1
if(($result=mysql_query("select * from my_table where id=$name"))) 

应该

if(($result==mysql_query("select * from my_table where id=$name"))) 
+0

由于双括号,他所做的方式是正确的,以检查mysql_query是否为false。因为他正在设置结果变量,所以不需要双等号。 – David

+1

即使没有双重修辞,它也是有效的。单等于变量将'mysql_query'的返回值赋值给$ result,并将其返回 - 因此,您将结果分配给$ result,并同时测试$ result是否为“true”。 ==比较从'mysql_query'到'$ result'的值的返回值 - 由于我怀疑$ result被定义,所以它可能是所需要的对象。 – Adam

0

对于SELECT,SHOW,描述,解释等语句返回的结果集 ,请求mysql_query()成功返回的资源,或 错误FALSE。 SQL语句,INSERT,UPDATE,DELETE,DROP等,mysql_query() 在成功时返回TRUE或在错误时返回FALSE。

要检查是否有返回行,你需要在你正在使用过时mysql_函数使用

mysql_num_rows() 

更多。

你应该开始mysqli_ or PDO准备好的声明。

相关问题