I'm wondering how I would issue a query from a PDO and have an array returned? Right now, I have

$DBH = new PDO("mysql:host={$host};dbname={$dbname}", $user, $pass);

Using a foreach loop, like so

$query = "SELECT DISTINCT City FROM Locations ORDER BY City";
foreach($DBH->query($query)as $row){
            echo $row['City'];      
            }

I can get all the cities printed. However, I would like to store all the cities into an array. I tried to do it like this

$array = $DBH->query($query);

but that didn't work at all. Any suggestions?

share|improve this question
feedback

3 Answers

up vote 2 down vote accepted

This question has been asked so many times.

$query = "SELECT DISTINCT City FROM Locations ORDER BY City";
foreach($DBH->query($query) as $row){
        $array[] = $row['City'];      
        }
share|improve this answer
This works, but I was hoping for a solution without loops – No_name Jun 27 '12 at 6:25
Not really possible, you have to iterate through results somehow. If you don't like looking at it in your code, encapsulate it as a function. But I don't see the point. – matthewdavidson Jun 27 '12 at 17:01
feedback

You're using PDO, so you should be using PDOStatement::fetchAll().

$stmt = $DBH->query($query);
$array = $DBH->fetchAll(PDO::FETCH_COLUMN);

Done - And you're not using any loops.

share|improve this answer
wouldn't just plain fetchAll() return a nested array instead of one array with all city values? – Aaron W. Jun 25 '12 at 21:06
Yeah you should be indexing. – matthewdavidson Jun 25 '12 at 21:13
1  
Psst, ->fetchALL(PDO::FETCH_COLUMN);.... – Wrikken Jun 25 '12 at 21:21
Good call @Wrikken - Thanks! – nickb Jun 25 '12 at 21:54
Though I would prefer a loopless version like this, it simply doesn't work for me. When I tried echoing out the array with a foreach loop like below, I was able to get each city. With this, I don't even get anything. – No_name Jun 27 '12 at 4:34
feedback

Possibly try:

$array = array();

foreach($DBH->query($query) as $row){
    array_push($array, $row['City']);     
}

print_r($array);
share|improve this answer
should be array_push($array, $row['City']); – Aaron W. Jun 25 '12 at 20:59
Thanks for catching that. – John Robinson Jun 25 '12 at 20:59
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.