How to fetch all results of MySQLi prepared statem

2019-09-07 16:07发布

问题:

This question already has an answer here:

  • Get all objects without loop in OOP MySQLi 2 answers

How can I fetch all results as an associate array from a MySQLi prepared statement without needing to loop through the results one row at a time?

Take this example:

$results_st = $dbi->prepare("SELECT * FROM foobar");
$results_st->execute();
$results = $results_st->get_results();

// I would like something like:
$results_ar = $results->fetch_all(MYSQLI_ASSOC);

// this should print out all the results in an associate array.
print_r($results_ar);

Desired output would be similar to mysqli_fetch_all(MYSQLI_ASSOC) http://php.net/manual/en/mysqli-result.fetch-all.php

Array (
   [0] => (
      'title' => cat,
      'id' => 1
      ),
   [1] => (
      'title' => dog,
      'id' => 2
      ),
   [2] => (
      'title' => bird,
      'id' => 3
      )
);

回答1:

Use fetch_assoc()

$data = $result->fetch_assoc()


标签: php mysql mysqli