Mysqli Prepared Stmt返回0 num_rows

时间:2017-08-04 09:54:58

标签: php mysqli prepared-statement mysql-num-rows

帮助。我得到0 num_rows但是如果我在控制台中执行查询我得到了结果。我有点准备stmts。这是我的代码

数据库连接类:

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

登录课程:

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;
}
}

1 个答案:

答案 0 :(得分:2)

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

首先,如上所述,在绑定变量之前无需为变量赋值。这根本不是真的。这让我非常生气,因为我在stackoverflow上一遍又一遍地阅读这个...而且它错了。只是。错误。如果确实如此,则无法使用不同的值执行多个预准备语句。即使它的老人和许多人不喜欢在这里看到它,来自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;
}