I'm a little confused, PHP says $results is a non-object of the mysqli class

后端 未结 5 1985
北恋
北恋 2020-12-22 13:01

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:

相关标签:
5条回答
  • 2020-12-22 13:11

    Why are you checking if($results) after trying to manipulate it?

    This...

    $results->close();
    //...
    if(!$results){
        //...
    }
    

    Should be...

    if(!$results){
        //...
    }
    $results->close();
    
    0 讨论(0)
  • 2020-12-22 13:16

    You script is lacking error checking, and therefore the error in the query is not handled.

        $query = "SELECT user, password FROM Users 
        WHERE user = '$user' AND password = '$pass' " ;
        //           ^ quotes needed     
    
        echo $query;
    
        $results = $db->query($query);
    
        // handle a error in the query
        if(!$results)
          die($db->error);
    
        while ($row = $results->fetch_row()){
            echo htmlspecialchars($row->user);
            echo htmlspecialchars($row->password);
        }
    
    0 讨论(0)
  • 2020-12-22 13:16

    You have to check, if query runs properly:

    if ($result = $mysqli->query($query))
    {
    }
    

    Use: var_dump($results) to check what it contains

    0 讨论(0)
  • 2020-12-22 13:25

    Your query is failing on this line:

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

    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."' " ;
    

    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();
    
    0 讨论(0)
  • 2020-12-22 13:29

    If you user & password field text or varchar, then you need to use single quote around them

    $query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
    
    0 讨论(0)
提交回复
热议问题