Mysql num行总是想要1

时间:2015-02-17 23:07:38

标签: php mysql

这是我的代码:

   <?php

    $host="localhost";
    $user="root";
    $pass="";
    $db="comportal";

    mysql_connect($host, $user,$pass);
    mysql_select_db($db);


    if(isset($_POST['username'])){
    $username=$_POST['username'];
    $password=$_POST['password'];
    $sql="SELECT * FROM user WHERE username='".$username."' AND password='".$password."' LIMIT 1";
    $res= mysql_query($sql);

    if(mysql_num_rows($res)==1){
      echo "Successfully logged in.";
      exit();
     }
     else{
       echo "Invalid Information. Please return to the previous page.";
       exit();
     }
    }
    ?>

我总是得到这个错误:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\sample\login.php on line 20
Invalid Information. Please return to the previous page.

然后我尝试改变

  if(mysql_num_rows($res)==1){
  echo "Successfully logged in.";
  exit();

  if($res==true){
  echo "Successfully logged in.";
  exit();

但是,现在它在逻辑上是错误的。它表示即使没有存储在数据库中也能成功登录。

请问我该如何解决?

1 个答案:

答案 0 :(得分:0)

来自w3resource.com:

查询成功的SELECT,SHOW,DESCRIBE,EXPLAIN和其他语句的句柄,或者出错时查询错误。

因此,虽然您的查询可能没有返回任何行,但它仍然是一个成功的选择查询,因此为什么你得到if($ res == true)。

你为if(mysql_num_rows($ res)== 1)收到错误的原因是因为你已经用$ res = mysql_query($ sql)为它分配了一个布尔值;不是必需的int。

相关问题