0

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";
} 
1252748
  • 14,597
  • 32
  • 109
  • 229

2 Answers2

1

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']

inside the loop.


either

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

-- or --

$rows = $sth->fetchAll();
foreach($rows as $row) {
    ...
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks. I don't understand how the fetch() should be put inside the while loop(?) – 1252748 Feb 12 '13 at 18:24
  • I see. However, `foreach($result as $key=>$val) { echo $val . "\n"; }` simply displays `Array Array`. While `foreach($result as $key=>$val) { echo $val['StreetAddress1'] . "\n"; }` displays nothing. :/ I still can't see the data.. – 1252748 Feb 12 '13 at 18:36
0

$result = $sth->fetchAll();

$result will be an array with all your results.

Then use a foreach to loop through.

foreach

Zac
  • 1,605
  • 2
  • 13
  • 15
  • `foreach($result as $key=>$val) { echo $val;}` simply gives me `Array Array`, whereas `foreach($result as $key=>$val) { foreach($val as $k=>$v){ echo $v . "
    "; } }` prints out the first row of data twice (the number of rows in the table). How can I correct this? Thank you.
    – 1252748 Feb 12 '13 at 18:44