1

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?

3 Answers 3

3

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

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

Done - And you're not using any loops.

Sign up to request clarification or add additional context in comments.

2 Comments

wouldn't just plain fetchAll() return a nested array instead of one array with all city values?
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.
2
$query = "SELECT DISTINCT City FROM Locations ORDER BY City";

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

1 Comment

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

Possibly try:

$array = array();

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

print_r($array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.