我正在尝试从我的数据库中获取一些数据,然后将其传递到一个数组中供以后使用。我正在为我的驱动程序使用 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 note在 mysqli::fetch
上手册页,强调我的:
问题是 $row
返回的是引用而不是数据。
因此,当您编写 $array[] = $row
时,$array
将填充数据集的最后一个元素。
关于php - 从数据库获取数据时数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5304281/