Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO looping throug and printing fetchAll

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..

like image 212
Chris Avatar asked Oct 05 '09 12:10

Chris


People also ask

What does PDO fetchAll return?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is the difference between fetch and fetchAll?

if you want all records .. for fetch you are going to need to loop like while($row = $stmt->fetch()) { # work with the record } for fetchAll() you have direct acces to the records as a array.

Is fetchAll faster?

As expected, the fetchAll method is faster but require more memory.

What do you mean by PDO?

PDO is an acronym for PHP Data Objects.


1 Answers

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.

like image 144
Zed Avatar answered Sep 22 '22 09:09

Zed