php PDO 循环通过并打印 fetchAll

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1519872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:55:15  来源:igfitidea点击:

PDO looping throug and printing fetchAll

phpmysqldatabasepdofetchall

提问by Chris

I'm having trouble getting my data from fetchAll to print selectively.

我无法从 fetchAll 获取数据以进行选择性打印。

In normal mysql I do it this way:

在普通的 mysql 中,我这样做:

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)){
   $id = $row['id'];
   $n = $row['n'];
   $k = $row['k'];
}

In PDO, I'm having trouble. I bound the params, then I'm saving the fetched data into $rs like above, with the purpose of looping through it the same way..

在 PDO 中,我遇到了麻烦。我绑定了参数,然后像上面一样将获取的数据保存到 $rs 中,目的是以相同的方式循环遍历它..

$sth->execute();
$rs = $query->fetchAll();

Now comes the trouble part. What do I do PDO-wise to get something matching the while loop above?! I know I can use print_r() or dump_var, but that's not what I want. I need to do what I used to be able to do with regular mysql, like grabbing $id, $n, $k individually as needed. Is it possible?

现在是麻烦的部分。我该怎么做 PDO-wise 才能得到与上面的 while 循环匹配的东西?!我知道我可以使用 print_r() 或 dump_var,但这不是我想要的。我需要做我以前可以用常规 mysql 做的事情,比如根据需要单独抓取 $id、$n、$k。是否可以?

Thanks in advance..

提前致谢..

回答by Zed

It should be

它应该是

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
  $id = $row['id'];
  $n = $row['n'];
  $k = $row['k'];
}

If you insist on fetchAll, then

如果你坚持fetchAll,那么

$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
   $id = $row['id'];
   $n = $row['n'];
   $k = $row['k'];
}

PDO::FETCH_ASSOCfetches only column names and omits the numeric index.

PDO::FETCH_ASSOC仅获取列名并省略数字索引。