mysql 结果集转数组,Mysqli结果foreach结果集转换为数组

I know this is basic question but due to lack of knowledge, I want to know how mysqli_result converted to array and result was retrieved.

Here is the database:

CREATE TABLE IF NOT EXISTS `slider` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`title` varchar(255) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

INSERT INTO `slider` (`id`, `title`) VALUES

(1, 'Slider 1'),

(2, 'Slider 2'),

(3, 'Slider 3'),

(4, 'Slider 4'),

(5, 'Slider 5'),

(6, 'Slider 6'),

(7, 'Slider 7'),

(8, 'Slider 8');

Here is the PHP file:

$mysqli = new mysqli('host', 'user', 'pass', 'db',port);

if ($mysqli->connect_error) {

die('Connect Error (' . $mysqli->connect_errno . ') '

. $mysqli->connect_error);

}

$query = "SELECT * FROM slider ORDER BY id";

if ($result = $mysqli->query($query)) {

echo "

"; print_r($result); //This is mysqli_result Object

foreach($result as $row) { //Here is the magic how it is converted and row is retrieved

//echo "

"; print_r($row);

printf ("
%s (%s)\n", $row["id"], $row["title"]);

}

while ($row = $result->fetch_assoc()) { //Normal way

//echo "

"; print_r($row);

printf ("
%s (%s)\n", $row["id"], $row["title"]);

}

$result->free();

}

When we traverse through while, we do have to retrieve result using fetch_* methods but when I traverse through foreach, how result is retrieved? How implicitly, foreach loop is calling fetch_*?

解决方案

This question is not that basic actually, as this behavior is rather new, and indeed it employs some magic.

As you can read on the manual page, mysqli_result object supports Traversable interface, so it can be iterated over. And when iterated, it is calling fetch() internally.

So it is not converted but rather disguised as array.

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值