Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP PDO have a built in method to return a result as array with ID as key?

Say I have a table

id,f1,f2
10,'aaa','aaaaaa'
20,'bbb','bbbbb'

Is there a way using PDO to query the DB and get the results as array:

[10=>['aaa','aaaaa'], 20=>['bbb','bbbbb'] ]
like image 683
Itay Moav -Malimovka Avatar asked Nov 27 '25 06:11

Itay Moav -Malimovka


1 Answers

Yes, it's possible.
That's one of things that make PDO so great.

All you need is PDO::FETCH_UNIQUE constant:

$data = $pdo->query('SELECT id,f1,f2 FROM t')->fetchAll(PDO::FETCH_UNIQUE);

will give you desired result.

You may wish to browse other fetch modes for PDO in the article I wrote recently.

like image 84
Your Common Sense Avatar answered Nov 28 '25 21:11

Your Common Sense