Call to a Member Function fetch_object() on a non-object

Asked

Viewed 929 times

0

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

Call to a Member Function fetch_object() on a non-object at 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");

1 answer

1

Summary:

Change this:

 $user = $result->fetch_object();

For this:

 $user = $stmt->fetch();

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

If you really want to use fetch_object() you will have to use the driver mysqlnd. This will allow you to use the 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 the own documentation, you don’t have to believe me, the $result becomes a boolean value, true or false.

So do this:

$result = $stmt->store_result();

$user = $result->fetch_object();

Is equivalent to making:

$user = true->fetch_object();

Which logically won’t work.

When executing the $stmt->store_result() is the variable $stmt which stored the result and not the answer from store_result.

So you can get the answer in a variable outside the $stmt you will need to use the get_result(). Supposing you use $x = $stmt->get_result(), the get_result() will return the content, therefore the $x will have all the query output.

  • $stmt->get_result()->fetch_object(), I used your suggestion and the same error appears.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.