【发布时间】:2017-02-06 18:00:03
【问题描述】:
我在将 mysql 数据库中的数据检索到 php 数组时遇到问题。如果我执行下面的代码,查询会获取一些相应的行两次甚至 3 次。 我得到了一个列出名称和上传日期的文件数据库。 假设我有 4 个文件(经过测试): 文件 1、文件 2、文件 3、文件 4。 代码会回显(如果有帮助):
File1 and its date
File1 and its date
File4 and its date
File2 and its date
File2 and its date
File3 and its date
File3 and its date
File4 and its date
File4 and its date
代码如下:
$query = $pdo_con->query("SELECT * FROM uploads WHERE active = 1 and owner = '$current_user' Order By upload_id DESC");
while($r = $query->fetch(PDO::FETCH_ASSOC)) {
$new_array[] = $r;
$new_array[$r['name']] = $r;
$new_array[$r['uploaded']] = $r;
}
foreach($new_array as $array){
echo $array['name'];
echo $array['uploaded'];
}
我希望代码仅以正确的顺序回显每个文件一次(upload_id 的降序(自动递增))
【问题讨论】:
-
您将
$row多次添加到$new_array。每行 3 次。如果您希望它显示一次,则只添加一次。此外,pdo 确实有一个fetchAll方法,可以将所有行放入一个数组中。 -
如果您运行查询,您会在结果中看到多行吗?如果你没有对
$new_array做任何事情,为什么不直接回显或使用fetchAll()并循环呢?