Mysqli 准备 Stmt returns 0 num_rows

Mysqli Prepared Stmt returns 0 num_rows

求助。我得到 0 num_rows 但如果我在控制台中执行查询,我会得到结果。我对准备好的 stmts 有点陌生。这是我的代码

数据库连接class:

class DbConnection {
const  HOST = "localhost";
const  USR = "root";
const  PWD = "";
const  DB = "club_db";
}

登录class:

class UsrLogin extends DbConnection {

private $conn; /*db connector*/

/*login vars*/
private  $usr;
private  $pwd;

/*ctrl var*/
public $AccessGranted = false;

function __construct($username,$password){
    /*initialize db connection*/
    $this->conn = new mysqli(DbConnection::HOST,DbConnection::USR,DbConnection::PWD,DbConnection::DB);
    /*set login vars*/
    $this->usr = $username;
    $this->pwd = $password;

}

public function login(){
    $sql = "SELECT * FROM sys_usr WHERE uid = ? AND passwd = ?";
    $stmt = $this->conn->prepare($sql);
    $stmt->bind_param("ss", $usr,$pwd);

    $usr = $this->usr;
    $pwd = $this->pwd;

    $stmt->execute();

    echo  $stmt->num_rows;
}
}

虽然我认为这里给出的两个答案都不正确,但我想我知道问题出在哪里。

首先,如前所述,在绑定变量之前无需为变量赋值。那根本不是真的。这让我很生气,因为我在 Whosebug 上一遍又一遍地阅读这个……这是错误的。简单地。错误的。如果它是真的,您将无法执行具有不同值的多个准备好的语句。即使它很旧而且很多人不喜欢在这里看到它,来自 W3 的链接: https://www.w3schools.com/php/php_mysql_prepared_statements.asp 它表明你正在尝试的是完全可能的,它也表明你有准备好的陈述的可能性。

那么,现在解决你的问题:

你所做的一切都很好。但是您还缺少另一件事,我认为这就是导致错误的原因。缺少 store_result() 函数。

给这个代码一个机会,告诉我它是否有效:

public function login(){
    $sql = "SELECT * FROM sys_usr WHERE uid = ? AND passwd = ?";
    $stmt = $this->conn->prepare($sql);
    $stmt->bind_param("ss", $usr,$pwd);

    $usr = $this->usr;
    $pwd = $this->pwd;

    $stmt->execute();
    $stmt->store_result(); // Quite sure you need this to perform a num_rows...
    echo  $stmt->num_rows;
}