PDO looping throug and printing fetchAll(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.
这篇关于PDO 循环通过并打印 fetchAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PDO 循环通过并打印 fetchAll
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
