[英]Problems with array when getting data from a database
I'm trying to get some data from my database, and then pass it into an array for later use. 我正在尝试从我的数据库中获取一些数据,然后将其传递给一个数组供以后使用。 I am using MySQLi for my driver. 我正在使用MySQLi作为我的驱动程序。
Here's my code: 这是我的代码:
// 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);
The problem is, when this executes, the $skins
array contains the last result row from the query. 问题是,当执行此操作时, $skins
数组包含查询中的最后一个结果行。 This is the print_r of $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
)
)
As you can see, the last result from the query is populating all of the array entries for some reason. 如您所见,查询的最后结果是出于某种原因填充所有数组条目。
Can anyone explain this behaviour and tell me what I'm doing wrong? 谁能解释这种行为并告诉我我做错了什么? Thanks. 谢谢。 :) :)
EDIT: Here's the solution: 编辑:这是解决方案:
while($stmt->fetch())
{
foreach($result as $key=>$value)
{
$tmp[$key] = $value;
}
$skins[$i] = $tmp;
$i++;
}
Quoting the (now) first note on the mysqli::fetch
manual page, emphasis mine : 引用 mysqli::fetch
手册页上的(现在)第一个注释 ,强调我的:
the problem is that the $row
returned is reference and not data . 问题是返回的$row
是引用而不是数据 。
So, when you write $array[] = $row
, the $array
will be filled up with the last element of the dataset. 因此,当您编写$array[] = $row
, $array
将填充数据集的最后一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.