繁体   English   中英

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

[英]Problems with array when getting data from a database

我正在尝试从我的数据库中获取一些数据,然后将其传递给一个数组供以后使用。 我正在使用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++;
}

引用 mysqli::fetch手册页上(现在)第一个注释 ,强调我的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM