How to use mysqli_fetch_all in PHP correctly?

Asked

Viewed 1,500 times

1

I have a PHP function using Mysql, follows:

public function listAll(){
      $sql = mysqli_query($this->conectar, "SELECT * FROM items");
      $this->desconectar;
      return $sql->fetch_all();
    }

my page for instance:

$p = new Items();
$result = $p->listAll();
$r = new ArrayIterator($result);

print_r($r);

when I give a print_r in it returns me that ArrayIterator Object ( [storage:ArrayIterator:private] => Array ( [0] => Array ( [0] => 3 [1] => prod test 3)))

When I try to call the name it returns to me:

echo $r->current()->nome

Trying to get property of non-object in

result of print_r($result)

Array ( [0] => Array ( [0] => 3 [1] => prod test 3)

  • because it needs a ArrayIterator?

  • gives a print_r($result) and ask the question! maybe you don’t even need this Arrayiterator

  • Try using the MYSQLI_ASSOC parameter within the function

  • the error is saying that the result is not an object, I believe that because it returns an array of objects

  • Felipe I used as rray said but continues the mistake Trying to get property of non-object

1 answer

1


fetch_all() by default returns an array with numeric indices as shows the print_r() question. If you want that array returned if an associative uses the constant MYSQLI_ASSOC in the function call. If you want the return to be a precise object of the function mysqli_fetch_object() together with a while.

Change:

return $sql->fetch_all(); 

To:

return $sql->fetch_all(MYSQLI_ASSOC);

The method current() return the array then you can access it like this:

echo $r->current()['nome'];

Or else:

 $item = $r->current();
 echo $item['nome'] .' - '. $item['outra_chave'];
  • I used it but it continues with the error when I call the echo echo $r->current()->nome and also when I call it so echo $result->nome

  • when I use the $r->current() in the print_r he returns me right the value Array ( [id] => 3 [nome] => prod test 3) so then I try to access for example the id $r->current()->id he brings me error Trying to get property of non-object

Browser other questions tagged

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