3

So many questions about PDO::fetchAll() but still I can't find my answer. I need to fetch my results as it is returned by the MySQL. for example if I have columns id, name, age to be returned like this:

array(
   "id"=array(1,2,3),
   "name"=array("xy","by","cy"),
   "age" = array(32,34,35)
)

I know I can make a function and iterate through the list and put them in the array manually, but I want to know if there is a direct way using fetchAll('magic').

Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
Mohammad
  • 90
  • 7

1 Answers1

3

You can do like this.

<?php
function returnResultAsArray()
{
    $test=NULL;
    //  ..... connection and query here
    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    foreach($results as $row) 
    {
        $test['id'][]=$row['id'];
        $test['name'][]=$row['name'];
        $test['age'][]=$row['age'];
    }
    return $test;
}
?>

Let me know if this works for you

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Narayan Bhandari
  • 426
  • 3
  • 11
  • I have a function similar to this one, but I was thinking of a straight forward way, something like `var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));` I don't know which combinations I should use to get what I want. – Mohammad Jul 05 '15 at 06:34