Call to a member function fetch_object () on a non-object

0

In the following code, the following error occurs, which I can not understand why:

  

Call fetch_object () on a non-object on line 21

<?php
require('config.php');


if (isset($_POST['email']))
{
    $email = stripslashes($_REQUEST['email']);

    $email = mysqli_real_escape_string($conn,$email);
    $password = stripslashes($_REQUEST['password']);
    $password = mysqli_real_escape_string($conn,$password);

    $stmt = $conn->prepare("SELECT password FROM registo WHERE email=?");
    $stmt->bind_param("s",$email);
    $email = $_POST['email'];
    $stmt->execute();
    $result= $stmt->store_result();

    if($stmt->affected_rows > 0)
    {    
       $user = $result->fetch_object();//linha 21
        if(password_verify($password,$user->password))
        {
            $_SESSION['email'] = $email;
            $_SESSION['user'] = true;
            header("Location: home.php");
    
asked by anonymous 21.05.2017 / 18:58

1 answer

1

Summary:

Change this:

 $user = $result->fetch_object();

For this:

 $user = $stmt->fetch();

This will have the result in array, not in object .

If you really want to use fetch_object() you will have to use the mysqlnd driver. This will allow you to use get_result() .

$resultado = $stmt->get_result();
//...
$user = $resutado->fetch_object();

In this case:

$result = $stmt->get_result();

if($result->num_rows > 0)
{    
    $user = $result->fetch_object();//linha 21
    if(password_verify($password,$user->password))
    {
        $_SESSION['email'] = $email;
        $_SESSION['user'] = true;
        header("Location: home.php");

Now the explanation behind the error is simple.

When you use:

$result = $stmt->store_result();

According to own documentation , do not need to believe me , $result becomes a Boolean value, true or false .

So do this:

$result = $stmt->store_result();

$user = $result->fetch_object();

It's equivalent to doing:

$user = true->fetch_object();

That logically will not work.

When you run $stmt->store_result() it is the $stmt variable that stored the result and not the store_result response.

In order for you to get the answer in a variable out of $stmt you will need to use get_result() . Assuming you use $x = $stmt->get_result() the get_result() will return the content, so the $x will have all the result of the query.

    
21.05.2017 / 20:16