PDO 循环通过并打印 fetchAll

2021-12-26 00:00:00 database php mysql 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 中,我遇到了麻烦.我绑定了参数,然后像上面一样将获取的数据保存到 $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-wise 才能得到与上面的 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.

相关文章