Mysqli结果foreach结果集转换为数组 [英] Mysqli result foreach resultset converted to array

查看:514
本文介绍了Mysqli结果foreach结果集转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个基本问题,但是由于缺乏知识,我想知道mysqli_result如何转换为数组并检索结果.

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.

这是数据库:

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');

这是PHP文件:

$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 "<pre>"; 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 "<pre>"; print_r($row);
        printf ("<br>%s (%s)\n", $row["id"], $row["title"]);
    }   

    while ($row = $result->fetch_assoc()) { //Normal way
        //echo "<pre>"; print_r($row);
        printf ("<br>%s (%s)\n", $row["id"], $row["title"]);
    }

    $result->free();
}

遍历while时,确实必须使用fetch_ *方法检索结果,但是当我遍历foreach时,如何检索结果? foreach循环在调用fetch_ *时隐含了什么?

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.

作为,您可以在手册页上阅读 ,mysqli_result对象支持 Traversable接口,因此可以对其进行迭代.并且在迭代时,它在内部调用fetch().

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.

这篇关于Mysqli结果foreach结果集转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆