簡體   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