Using Column Value as Index in Results Using PDO
When working with SQL tables, it's often desirable to use a specific column's value as the index for query results. In this case, we have a table named 'brands' with columns id, name, and url, and we want to fetch all records while using the id values as the array indices.
While a loop could achieve this, a cleaner solution is available using PDO's fetch mode. The PDO::FETCH_UNIQUE option allows you to specify the index field for the resulting array.
Query using PDO::FETCH_UNIQUE:
$data = $pdo->query('SELECT * FROM brands')->fetchAll(PDO::FETCH_UNIQUE);
This line of code will fetch all records from the 'brands' table and return an array where the indices are the id values from the column.
Output:
1 => array ( 'name' => 'Solidfloor', 'url' => 'solidfloor', ), 2 => array ( 'name' => 'Quickstep', 'url' => 'quickstep', ), 4 => array ( 'name' => 'Cleanfloor', 'url' => 'cleanfloor', ),
By using PDO::FETCH_UNIQUE, we can efficiently retrieve query results with custom indices, providing greater flexibility and ease of handling.
The above is the detailed content of How to Use a Column Value as the Index in PDO Query Results?. For more information, please follow other related articles on the PHP Chinese website!