本文介绍了PDO循环通道和打印fetchAll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在正常的mysql中我这样做:

In normal mysql I do it this way:

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

在PDO中,我遇到了问题。我绑定了params,然后我将获取的数据保存到$ rs像上面,目的是循环通过它的方式相同。

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..

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

现在是麻烦的部分。我做什么PDO明智的得到匹配上面的while循环?我知道我可以使用print_r()或dump_var,但这不是我想要的。我需要做我以前能够使用普通的mysql,比如根据需要单独抓取$ id,$ n,$ k。可能吗?

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?

提前感谢..

推荐答案

应为

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

如果您坚持 fetchAll ,然后

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

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

PDO::FETCH_ASSOC fetches only column names and omits the numeric index.

这篇关于PDO循环通道和打印fetchAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 19:23
查看更多