2015-02-17 73 views
-2

这是我的代码:Mysql的NUM行总是要1

<?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(); 

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

请问我该如何解决?

+0

可能重复的[mysql \ _fetch \ _array()期望参数1是资源(或mysqli \ _result),布尔给定](http://stackoverflow.com/questions/2973202/mysql-fetch-array-expects -parameter -1-待资源或-mysqli的对结果布尔) – 2015-02-17 23:12:57

回答

0

从w3resource.com:

查询手柄成功SELECT,SHOW,描述,解释等语句或FALSE的错误。

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

你得到if(mysql_num_rows($ res)== 1)错误的原因是因为你用$ res = mysql_query($ sql)给它赋了一个布尔值;根据需要不是int。