我有点困惑,PHP说$ results是mysqli类的一个非对象 [英] I'm a little confused, PHP says $results is a non-object of the mysqli class

查看:72
本文介绍了我有点困惑,PHP说$ results是mysqli类的一个非对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mysqli-> fetch_row()(或fetch_object(),fetch_array())来获取结果,但是当我在运行时运行代码时,会出现以下错误:

I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:

致命错误:在第23行上的...上的非对象上调用成员函数fetch_row().

要执行此操作的变量是$ result,结果在下面的代码中. $ user和$ password从另一个包含该文件的.php文件中获取它们的值,因此目前并不十分重要.现在纠正我,如果我错了,但是如果将$ results设置为= $ db-> query($ query),那么它不应该继承mysqli类的$ db属性吗?

The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?

class mySQLHelper{

    public function checkPass($user, $pass){
        global $db;
        $db =  new mysqli();
        $db->connect('localhost', 'root', '', 'mydb');
        if (mysqli_connect_errno()){
            echo 'Can not connect to database';
            echo mysqli_connect_errno(). mysqli_connect_error();
            exit;
            return false;
        }


        $query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;

       echo $query;

        $results = $db->query($query);

        while ($row = $results->fetch_row()){

            echo htmlspecialchars($row->user);
            echo htmlspecialchars($row->password);


        }

        $results->close();

        $url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
        if(!$results){
         //   mysqli_close($db);
          //  header("Location:.$url.login.php&msg=1");

        }

        else{
        //    mysqli_close($db);
        //    header("Location:.$url.featured.php");


        }

    }

}

推荐答案

您的查询在此行失败:

$results = $db->query($query);

因此,$resultsfalse-不是您期望的结果对象.

Because of this, $results is false - not a result object as you expect.

要解决此问题,您需要在变量周围添加引号(或使用准备好的语句):

To fix the issue, you need to add quotes around your variables (or use prepared statements):

$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;

我建议更新以使用准备好的语句来防止SQL注入问题,但是:

I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:

$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();

这篇关于我有点困惑,PHP说$ results是mysqli类的一个非对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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