Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO associative arrays - return associative

I have this code:

$dbInstance = DB_Instance::getDBO();
$statement = $dbInstance->prepare("SELECT id, name FROM language ORDER BY id");
$statement->execute();      
$rows = $statement->fetchAll(); 

//Create associative array wuth id set as an index in array
$languages = array();
foreach($rows as $r) {
    $languages[$r['id']] = $r['name'];
}
return $languages;

I can't figure out how to use PDO-statement to achieve the same result that array $languages produces. I've tried some different fetch_styles.

I've tried some different styles and I could get like:

[0] svenska
[1] engelska

but I want like:

[1] svenska
[2] engelska

(where 1 and 2 are the values of id in database)

I guess I could create a function and call that with FETCH_FUNC but I'm not sure that would be so great either.

Is the above the best/cleanest way to do it?

like image 308
bestprogrammerintheworld Avatar asked Mar 20 '13 00:03

bestprogrammerintheworld


Video Answer


1 Answers

Everybody forgot about the

$sth->fetchAll(PDO::FETCH_KEY_PAIR);
like image 159
Miron Yanovskiy Avatar answered Oct 12 '22 21:10

Miron Yanovskiy