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?
Everybody forgot about the
I think you might be looking for
$result = $sth->fetch(PDO::FETCH_ASSOC);
Reference: http://php.net/manual/en/pdostatement.fetch.php
[edit] oops to late :)
Not really sure if there's any better way. You could try this?
There's nothing wrong with foreach loops. I'd actually use what you've got. It's hard to get cleaner than that...
UPDATE:
After carefully re-reading your question, what you REALLY should be asking is whether you can format your QUERY in such a way that the results are returned in a different format.
The way that your normal SELECT query is returned is thusly:
What you're asking for is for some way to return your query results like THIS:
I'm not entirely sure you CAN do this in SQL, to be perfectly honest. I would also recommend against it, even if you could. It would be horrendous for a scaling table. If your table is static, then why not format it in the way I just mentioned to begin with? Why not just have it in a static PHP array in an include file?