How to use mysqli_fetch_all in PHP correctly?

1

I have a function in PHP using MySQL, it 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 it returns me this ArrayIterator Object ( [storage:ArrayIterator:private] => Array ( [0] => Array ( [0] => 3 [1] => prod test 3)))

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

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)

    
asked by anonymous 14.11.2017 / 15:45

1 answer

1

fetch_all() by default returns an array with numeric indexes as print_r() in the question. If you want this array returned if an associative uses the MYSQLI_ASSOC constant in the function call. If you want the return to be an object you need the mysqli_fetch_object() function in conjunction with a while.

Change:

return $sql->fetch_all(); 

To:

return $sql->fetch_all(MYSQLI_ASSOC);

The method current() returns the array so you can access it like this:

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

Or:

 $item = $r->current();
 echo $item['nome'] .' - '. $item['outra_chave'];
    
14.11.2017 / 16:00