Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using value of a column as index in results using PDO

Tags:

arrays

sql

php

pdo

I have an SQL table called 'brands' with the columns id, name, url. In that table I have this data set:

1, Solidfloor, solidfloor;
2, Quickstep, quickstep;
4, Cleanfloor, cleanfloor;
5, Blue Dolphin, blue-dolphin;
6, Krono, krono;
8, Meister, meister;

I'm fetching them all right now and I get a nice array in return, but, I need the index of the arrays to not be an incremented number, but the id of that particular row. I could of course loop through the result set, but is there a cleaner way of doing this?

like image 954
Farid El Nasire Avatar asked Oct 11 '12 07:10

Farid El Nasire


People also ask

What does PDO fetchAll return?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

How does PDO select data?

First, connect to a MySQL database. Check it out the connecting to MySQL database using PDO tutorial for detail information. Then, construct a SELECT statement and execute it by using the query() method of the PDO object. The query() method of the PDO object returns a PDOStatement object, or false on failure.

What is the use of index in phpmyadmin?

Indexes are used when you need to retrieve certain information from a table regularly. For example, if you have a users table, and you will need to access the email column a lot, then you can add an index on email, and this will cause queries accessing the email to be faster.


1 Answers

Although PDO::FETCH_UNIQUE description in PHP manual is quite unclear, but in fact it's exact parameter you actually need.

$data = $pdo->query('SELECT * FROM table')->fetchAll(PDO::FETCH_UNIQUE);

is giving you an array indexed by the field listed in SELECT clause first (when * is used then first field in the table definition, which should be id in your case).

Note that by default using just PDO::FETCH_UNIQUE will give you resulting rows with doubled values. You can either add preferred row mode to this call or - better, set it once for all PDO calls in constructor or via setAttribute(). The output below is shown for PDO::FETCH_ASSOC set as default fetch mode.

  1 => array (
    'name' => 'Solidfloor',
    'url' => 'solidfloor',
  ),
  2 => array (
    'name' => 'Quickstep',
    'url' => 'quickstep',
  ),
  4 => array (
    'name' => 'Cleanfloor',
    'url' => 'cleanfloor',
  ),
)
like image 64
Your Common Sense Avatar answered Sep 26 '22 04:09

Your Common Sense