1

How does one destructure a row from a mysqli_result? This pattern works with PDO, but I'd like to be able to use the same with mysqli.

<?php
$mysqli = new mysqli('', 'pdo', '123', 'pdo');
foreach ($mysqli->query("select uid, name from users") as [$uid, $name])
  print("$uid: $name\n");

// PHP Warning:  Undefined array key 0 on line 3
// PHP Warning:  Undefined array key 1 on line 3
Dharman
  • 30,962
  • 25
  • 85
  • 135
XTF
  • 1,091
  • 1
  • 13
  • 31

1 Answers1

1

You can only iterate mysqli_result using associative arrays.

foreach ($mysqli->query("select uid, name from users") as ['uid' => $uid, 'name' => $name]) {
    print "$uid: $name\n";
}

However, I would advise using fetch_all() which will fetch everything into an array, even using numerical keys.

$result = $mysqli->query("select uid, name from users")->fetch_all(MYSQLI_NUM);
foreach ($result as [$uid, $name]) {
    print "$uid: $name\n";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • `fetch_all()` is sub optimal, especially for larger results, but it seems to be the only supported way. – XTF Mar 20 '21 at 09:35