准备 Select 语句和获取结果

Prepared Select Statement and Fetching Results

我对 Prepared Select 语句以及存储和获取结果有疑问。下面的代码允许用户登录。代码首先检查数据库中是否有匹配的记录,然后将用户重定向到欢迎页面。我很确定问题在于语句:$stmt->num_rows;然后从 $stmt 中获取结果。任何帮助将不胜感激。

我有以下代码:

 if ($user == "" || $pass == "")
{
$error = "<span class='error'>You must enter the username and password</span><br /><br />";

}
else
{
    $query = "SELECT UserName,Password,Role FROM Users
        WHERE UserName=? AND Password=?";


    $stmt = $db->prepare($query);
    $stmt->bind_param("ss", $user, $pass);
    $stmt->execute();
    $stmt->store_result();

   $stmt->num_rows;


    if ($stmt == 0) 
    {
        $error = "<span class='error'>Incorrect Username/Password
                  </span><br /><br />";
    }
    else
    {    for ($i=0; $i <$stmt; $i++) {
    $row = $stmt->fetch_assoc();
    $role = $row['Role'];

        $_SESSION['user'] = $user;
        $_SESSION['pass'] = $pass;
        $_SESSION['role'] = $role;

       header( "Location: welcome.php" ); //will redirect to pool list after succesful login
        die ("You are now logged in. ");
       }
    }
  }
}

看来我想通了。代码如下:

    $query = "SELECT UserName,Password,Role FROM Users
        WHERE UserName=? AND Password=?";


    $stmt = $db->prepare($query);
    $stmt->bind_param("ss", $user, $pass);
    $stmt->execute();
    $stmt->store_result();
    $numrows = $stmt->num_rows;
    $stmt->bind_result($user, $pass, $role);



    if ($numrows == 0) 
    {
        $error = "<span class='error'>Incorrect Username/Password
                  </span><br /><br />";
    }
    else
    {    for ($i=0; $i <$numrows; $i++) {
    $row = $stmt->fetch();


        $_SESSION['user'] = $user;
        $_SESSION['pass'] = $pass;
        $_SESSION['role'] = $role;

       header( "Location: welcome.php" ); //will redirect to pool list after succesful login
        die ("You are now logged in. Please <a href='members.php?view=$user'>" .
            "click here</a> to continue.<br /><br />");