2011-03-14 123 views
3

我试图从数据库中获取一些数据,然后将其传递到数组中以供将来使用。我正在使用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数组包含从查询的最后结果行。这是$兽皮的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++; 
} 

回答

1

Quoting the (now) first notemysqli::fetch手册,重点煤矿:

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

+0

完美,谢谢。我会用解决方案编辑我的文章,并尽可能地接受您的答案。 – Josh 2011-03-14 20:56:03

+0

不客气:-)玩得开心! – 2011-03-14 20:56:52

相关问题