Trouble indexing MySQLi object in PHP

Viewed 47

I am able to successfully iterate through said MySQLi object in a foreach loop like so:

// Retrieving accounts
$stmt = $conn->prepare("SELECT * FROM accounts");
$stmt->execute();
$accounts = $stmt->get_result();

// Iterating over object
foreach ($accounts as $account) {
    print_r($account);
}

...hence, I thought this would work, too:

print_r($accounts[0]);

...but it doesn't, as I receive this error message:

Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array

Does anyone know how I would correctly index a MySQLi object similar to what I'm trying, if possible?

2 Answers

Although PHP's primary collection is an array, it also supports custom collections using an object through the Iterator and Traversable interfaces. The latter interface is not intended for user-land code, but core and extensions can use it and implement their own logic, and that's what get_result actually does. That interface also doesn't give any actual methods, it is just an identifier basically for the foreach construct:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

If mysqli had supported Iterator instead, you would have access to key-based indexes, but I'm guessing they really didn't make sense for mysql to do.

I've solved my issue by simply changing

$accounts = $stmt->get_result();

to

$accounts = $stmt->get_result()->fetch_all(); 

in the first code sample

Related