Mysqli Prepared Stmt返回0 num_rows [英] Mysqli Prepared Stmt returns 0 num_rows

查看:94
本文介绍了Mysqli Prepared Stmt返回0 num_rows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Help. I am getting 0 num_rows but if i execute the query in the console i am getting results. I m kinda new to prepared stmts. Here is my code

数据库连接类:

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

推荐答案

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

While in my opinion the two given answers here are not correct, I think I know where the problem is.

首先,如前所述,绑定变量之前无需为变量赋值.那根本不是真的.这让我非常生气,因为我在这里一遍又一遍地阅读了关于stackoverflow的内容……及其错误.简单地.错误的.如果是这样,您将无法执行具有不同值的多个准备好的语句.即使它的旧时和很多人不喜欢在这里看到它,W3的一个链接: https://www.w3schools.com/php/php_mysql_prepared_statements.asp 它表明您正在尝试的事情是完全可能的,它还显示了准备好的语句的可能性.

Well first, as said, no need to assign values to variables before you bind them. Thats not true at all. It makes me quite angry, because I read this over and over here on stackoverflow... and its wrong. Simply. Wrong. If it would be true, you couldn't perform multiple prepared statements with different values. Even if its old and many people don't like to see it here, a olink from W3: https://www.w3schools.com/php/php_mysql_prepared_statements.asp It shows that what you're trying is totally possible and it also shows the possibility that you have with prepared statements.

所以,现在解决您的问题:

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

What you're doing is totally fine. But there's another thing you're missing, and I think thats what cause the error. The missing store_result() function.

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

Give this code a chance and tell me if it works:

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

这篇关于Mysqli Prepared Stmt返回0 num_rows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆