【问题标题】:Problems with array when getting data from a database从数据库获取数据时数组的问题
【发布时间】:2011-07-15 07:50:41
【问题描述】:

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

【问题讨论】:

    标签: php arrays mysqli prepared-statement


    【解决方案1】:

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

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

    【讨论】:

    • 完美,谢谢。我将使用解决方案编辑我的帖子,并在可能的情况下接受您的回答。
    猜你喜欢
    • 2011-11-16
    • 2013-04-17
    • 1970-01-01
    • 2019-11-12
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多