Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php PDO fetchAll(), simple result

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

like image 401
Mohammad Avatar asked Aug 09 '26 20:08

Mohammad


1 Answers

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

like image 191
Narayan Bhandari Avatar answered Aug 11 '26 11:08

Narayan Bhandari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!