Using value of a column as index in results using PDO

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',
  ),
)

Leave a Comment