php - 从数据库获取数据时数组的问题

标签 php arrays mysqli prepared-statement

我正在尝试从我的数据库中获取一些数据,然后将其传递到一个数组中供以后使用。我正在为我的驱动程序使用 MySQLi。

这是我的代码:

// Build a query to get skins from the database
$stmt = $mysqli->prepare('SELECT id, name, description, author, timestamp, url, preview_filename FROM `skins` LIMIT 0, 5');
$stmt->execute();
$stmt->bind_result($result['id'], $result['name'], $result['desc'], $result['auth'], $result['time'], $result['url'], $result['preview']);

// The skins array holds all the skins on the current page, to be passed to index.html
$skins = array();
$i = 0;
while($stmt->fetch())
{
    $skins[$i] = $result;
    $i++;
}

print_r($skins);

问题是,执行此操作时,$skins 数组包含查询的最后一个结果行。这是 $skins 的 print_r:

Array
(
    [0] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

    [1] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

    [2] => Array
        (
            [id] => 3
            [name] => sdfbjh
            [desc] => isdbf
            [auth] => dfdf
            [time] => 1299970810
            [url] => http://imgur.com/XyYxs.png
            [preview] => 011e5.png
        )

)

如您所见,出于某种原因,查询的最后结果填充了所有数组条目。

任何人都可以解释这种行为并告诉我我做错了什么吗?谢谢。 :)

编辑:解决方案如下:

while($stmt->fetch())
{
    foreach($result as $key=>$value)
    {
        $tmp[$key] = $value;
    }
    $skins[$i] = $tmp;
    $i++;
}

最佳答案

Quoting the (now) first notemysqli::fetch 上手册页,强调我的:

问题是 $row 返回的是引用而不是数据
因此,当您编写 $array[] = $row 时,$array 将填充数据集的最后一个元素。

关于php - 从数据库获取数据时数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5304281/

相关文章:

javascript - 从 Javascript 输入变量到 Mysqli 数据库

php - 在 MySQL 中使用 mysqli 插入数据

php - 两个表的 SQL 计数

php - dropzone.js 发送空 $_FILES

php - 如何将 HTML 表单中的数字添加到数据库中已有的数字?

php - 在编码的 PHP 包含中覆盖 CSS

java - java中用公式nPr组合数组中的字符

php - 如何检查 PHP 数组是关联数组还是顺序数组?

javascript - 在javascript中将坐标存储在数组中

php - 将 mysql_connect 更改为 mysqli 导致功能失败