Created
February 26, 2014 21:48
-
-
Save betweenbrain/9239337 to your computer and use it in GitHub Desktop.
PHP PDO Fetch Array of Objects Indexed on Column Value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$sql = "SELECT id, name FROM `users`"; | |
try | |
{ | |
$query = $pdo->prepare($sql); | |
$query->execute(); | |
} | |
catch (PDOException $e) | |
{ | |
print "Error!: " . $e->getMessage() . "<br/>"; | |
die(); | |
} | |
// Returns an array of standard class objects indexed on `id` | |
$results = $query->fetchAll(PDO::FETCH_OBJ|PDO::FETCH_GROUP); | |
// Strip the useless numbered array out of each object | |
$results = array_map('reset', $results); | |
/* | |
[42] => stdClass Object | |
( | |
[name] => Bob Jones | |
) | |
[10] => stdClass Object | |
( | |
[name] => Sam Bodee | |
) | |
[18] => stdClass Object | |
( | |
[name] => Alex Xela | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment