mysqli_stmt_num_rows($stmt)总是返回0



我正在为我的web应用程序创建一个登录脚本,并尝试使用$count = mysqli_stmt_num_rows($stmt);来查找从sql select语句返回的行数,这样我就可以决定是否应该启动会话。

问题是,即使我输入了与数据库中的数据匹配的有效用户名和密码,$count也始终为0。我已经测试了select语句,它运行良好。没有给出错误、语法、SQL或其他方面的信息,所以我有点纠结于发生了什么。

代码:

<?php
    $link = mysqli_connect("localhost", "****", "****", "****");
    //check connection
    if (mysqli_connect_errno()) {
        printf("Connect failed: %sn", mysqli_connect_error());
        exit();
    }
    // username and password sent from form 
    $myusername=$_POST['myusername'];   
    $mypassword=$_POST['mypassword']; 
// Move to MySQL(i) as MySQL is now obslete and use Prepare statment for protecting against SQL Injection in better and easier way
    $stmt = mysqli_prepare($link, 'SELECT username, password FROM `users` WHERE  `username` =  ? AND  `password` =  ?');
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "ss", $myusername, $mypassword);
    /* execute query */
    mysqli_stmt_execute($stmt);
    /*count number of rows returned*/
    $count = mysqli_stmt_num_rows($stmt);
    /*display number of rows returned*/
    //echo $count;
    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $myusername, $mypassword);
    /* fetch value */
    mysqli_stmt_fetch($stmt);
    /* close statement */
    mysqli_stmt_close($stmt);
    if($count == 1) {
        session_start();
        $_SESSION['userid'] = $myusername;
        header("location:index.php");
        exit;
    } else {
        echo "Wrong Username or Password";
        echo "<form name='form5' action='main_login.html'>";
        echo    "<input type='submit' name='Submit' value='Log-in'>";
        echo "</form>";
    }
/* close connection */
mysqli_close($link);
?>

+1用于使用准备好的语句。

您需要先致电store_result,然后才能查看num_rows:

mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);

正如其他用户建议的那样,请确保您只在DB中存储哈希密码,而不是在HTTP请求中传输未加密的密码。您可以通过使用JS向表单添加输入,对登录表单上的密码进行哈希处理,使用JS删除未哈希的密码字段,并将表单中的哈希密码与数据库中的哈希口令进行比较。

此外,如果检查失败,最好使用自引用表单,而不是为后续登录回显新表单,这种方法很快就会变得难以管理。

+1到@leemo,以便首先回答,但我将扩展解释并将我的答案标记为CW。

MySQL客户端在获取所有行之前,无法知道结果集中有多少行。事实上,这并不是因为PHP——即使你直接使用MySQL客户端库用C编程,这也是真的。

因此,您要么需要像@leemo所说的那样使用mysqli_stmt_store_result(),它基本上将完整的结果集从服务器复制到客户端。

或者,您可以在mysqli_stmt_fetch()上循环,直到提取完所有行。然后mysql_stmt_num_rows()将返回正确的数字。

最新更新