在 PHP 中索引 MySQLi 对象时遇到问题
Trouble indexing MySQLi object in PHP
我能够像这样在 foreach 循环中成功迭代所述 MySQLi 对象:
// Retrieving accounts
$stmt = $conn->prepare("SELECT * FROM accounts");
$stmt->execute();
$accounts = $stmt->get_result();
// Iterating over object
foreach ($accounts as $account) {
print_r($account);
}
...因此,我认为这也行得通:
print_r($accounts[0]);
...但它没有,因为我收到此错误消息:
Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array
有谁知道我如何正确索引类似于我正在尝试的 MySQLi 对象(如果可能)?
虽然PHP的主要集合是数组,但它也支持通过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
使用对象的自定义集合。该接口也没有提供任何实际方法,它基本上只是 foreach
构造的标识符:
Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
如果 mysql我支持 Iterator,您将可以访问基于键的索引,但我猜 mysql 这样做确实没有意义。
我已经通过简单的更改解决了我的问题
$accounts = $stmt->get_result();
至
$accounts = $stmt->get_result()->fetch_all();
在第一个代码示例中
我能够像这样在 foreach 循环中成功迭代所述 MySQLi 对象:
// Retrieving accounts
$stmt = $conn->prepare("SELECT * FROM accounts");
$stmt->execute();
$accounts = $stmt->get_result();
// Iterating over object
foreach ($accounts as $account) {
print_r($account);
}
...因此,我认为这也行得通:
print_r($accounts[0]);
...但它没有,因为我收到此错误消息:
Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array
有谁知道我如何正确索引类似于我正在尝试的 MySQLi 对象(如果可能)?
虽然PHP的主要集合是数组,但它也支持通过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
使用对象的自定义集合。该接口也没有提供任何实际方法,它基本上只是 foreach
构造的标识符:
Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
如果 mysql我支持 Iterator,您将可以访问基于键的索引,但我猜 mysql 这样做确实没有意义。
我已经通过简单的更改解决了我的问题
$accounts = $stmt->get_result();
至
$accounts = $stmt->get_result()->fetch_all();
在第一个代码示例中