15

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

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

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();

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?

Thanks in advance..

questionto42
  • 7,175
  • 4
  • 57
  • 90
Chris
  • 8,736
  • 18
  • 49
  • 56

1 Answers1

34

It should be

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

If you insist on fetchAll, then

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

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

arshovon
  • 13,270
  • 9
  • 51
  • 69
Zed
  • 57,028
  • 9
  • 76
  • 100
  • thanks very much for your help. I went with 2, because I have to count it too before looping. So makes more sense to store it in $results before. – Chris Oct 05 '09 at 14:11
  • 2
    $query->rowCount() _might_ return the count. – Zed Oct 05 '09 at 14:22
  • 2
    It won't for SELECT statements. See this question: http://stackoverflow.com/questions/460010/work-around-for-php5s-pdo-rowcount-mysql-issue/660032#660032 – Imran Dec 15 '09 at 04:49
  • 1
    You have an extra right parentheses in this line: `$results = $query->fetchAll(PDO::FETCH_ASSOC));` – Zetaphor Dec 03 '14 at 22:43
  • The while loop does not show anything, at least it does not break the process either. The foreach loop shows the results (I use a dummy query `SHOW TABLES` which should not be the problem). I am fine with the foreach solution, just wondering why. – questionto42 Dec 27 '21 at 19:57