从postgre PDO返回多行 [英] returning multiple rows from postgre PDO

查看:120
本文介绍了从postgre PDO返回多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此PHP postgreSQL PDO语句未返回任何结果.我希望看到几行.我做错了什么?如何检索它们并将它们放入对象或数组中?

I get no results returned with this PHP postgreSQL PDO statement. I expected to see several rows. What have I done wrong? How can I retrieve them and put them into an object or array?

$sth = $dbh->prepare('SELECT * FROM address');
$sth->execute();

$result = $sth->fetch(PDO::FETCH_ASSOC);
while($row = $sth->fetch()) {  
    echo $row['StreetAddress1'] . "\n";
} 

推荐答案

考虑结果集的堆栈,每个fetch()调用都会弹出结果行.您在while循环之外调用了一次fetch,然后显然将$ result丢弃了.这意味着一行结果数据不见了.至于将它们放入对象/数组中,则取决于您.可能很简单:

Consider the result set a stack, and each fetch() call pops off a result row. You've called fetch once OUTSIDE of the while loop, and then apparently thrown away $result. That means one row of result data is gone. As for putting them into an object/array, that's up to you. could be as simple as:

$addresses[] = $row['StreetAddress1']

在循环内部.

两个

while($row = $sth->fetch()) {
   ...
}

-- or --

$rows = $sth->fetchAll();
foreach($rows as $row) {
    ...
}

这篇关于从postgre PDO返回多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆