php - 对查询结果使用 foreach() 而不是 while()

标签 php mysql foreach

我让这段代码工作了(我想)。

$sql = "SELECT
          order.id,
          order.date
        FROM
          order";
$result = mysql_query($sql) or die(mysql_error());
$rows = mysql_fetch_assoc($result);

foreach($rows as $row){
  echo $row['id'].": ".$row['date']."<br>";
}

结果与我使用的结果相同:

while($row = mysql_fetch_assoc($result)){
  echo $row['id'].": ".$row['date']."<br>";
}

但奇怪的是,今天它停止工作了。或者从来没有,但后来我变得有点疯狂。

我想使用 foreach(),因为数组 $rows 也可以“手动”填充,而不是通过查询填充。

我做错了什么......?

最佳答案

这从来没有(正常)发挥过作用。 mysql_fetch_assoc() 仅返回一行,您的 foreach 只是迭代结果集中第一行的列。

如果不先使用 while(或 for)循环将结果行提取到数组中,则无法使用 foreach

如果您想使用foreach,正如您所说,请执行以下操作:

 $rows = array();
 while ($row = mysql_fetch_assoc($result)) {
     $rows[] = $row;
 }

 foreach ($rows as $row) {
     // ...
 }

此外,please, don't use mysql_* functions in new code 。它们不再维护and are officially deprecated 。请参阅red box ?了解 prepared statements相反,并使用 PDO ,或MySQLi -this article将帮助您决定哪个。如果您选择 PDO,here is a good tutorial .

关于php - 对查询结果使用 foreach() 而不是 while(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15500940/

相关文章:

javascript - 在angularjs中使用JSONObject读取json

php - 如何根据值显示多个表格

mysql - 存储数周的扩展数据

java - Java 8 中的 ArrayList 交叉匹配

c# - 从嵌套 Foreach 中的 Observable 集合中删除项目

php - laravel 和 artisan 错误无法在迁移时添加外键

php - jQuery 只在用户第一次进入网站时起作用

PHP 压缩来自 Gopro 的视频,最好的方法?

PHP MySQL 插入文件,使用带有 OR 运算符的 IF 语句验证表单

javascript - 使用 forEach 在多个数组中搜索字符串