user116032 user116032 - 2 years ago 127
PHP Question

mysql ->fetch_all() not working

Please shame me. What's not right here? I was hoping for something like ->fetch_all(Opt), a one liner, to place all the results in an array but couldn't make it work. This is what I wound up doing:

$s = "select id, username from users";
$conn = db_connect();
$sth = $conn->prepare($s);
$sth->bind_result($id, $un);
$ida = array();
while ($sth->fetch()) {
$ida[] = $id;

I tried

$r = $sth->fetch_all()
(tried assigning and not assigning a return value) both using and not using

but both failed. What am I doing wrong?

Answer Source

First off, make sure that you have mysqlnd on your environment.

Then, to use ->fetch_all(), you'll need to use ->get_result() method first.

Here's the sequence:

$s = "select id, username from users"; 
$conn = db_connect();
$sth = $conn->prepare($s);
$data = $sth->get_result(); // get result first
$result = $data->fetch_all(MYSQLI_ASSOC); // then fetch all
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download