Skip to content

Instantly share code, notes, and snippets.

@cviebrock
Last active August 14, 2024 19:13
Show Gist options
  • Save cviebrock/a9113d2936e67c0d8065b83f8fa8be81 to your computer and use it in GitHub Desktop.
Save cviebrock/a9113d2936e67c0d8065b83f8fa8be81 to your computer and use it in GitHub Desktop.
Fun with PDO
$sql = 'SELECT id, name, email FROM USERS';
$users = $db->query($sql)->fetchAll(PDO::FETCH_OBJ);
[
  0 => {id: 123, name: "John", email: "john@example.com"},
  1 => {id: 278, name: "Mary", email: "mary@example.com"},
  2 => {id: 390, name: "Evan", email: "evan@example.com"},
]

PDO::FETCH_UNIQUE uses the first column in the query as the key for the result set:

$users = $db->query($sql)->fetchAll(PDO::FETCH_OBJ|PDO::FETCH_UNIQUE);
[
  123 => {name: "John", email: "john@example.com"},
  278 => {name: "Mary", email: "mary@example.com"},
  390 => {name: "Evan", email: "evan@example.com"},
]

If you want to keep that column in the objects as well, you will need to add it to the query twice:

$sql = 'SELECT id, id, name, email FROM USERS';
$users = $db->query($sql)->fetchAll(PDO::FETCH_OBJ);
[
  123 => {id: 123, name: "John", email: "john@example.com"},
  278 => {id: 278, name: "Mary", email: "mary@example.com"},
  390 => {id: 390, name: "Evan", email: "evan@example.com"},
]

This saves having to do the "normal" query, then loop through the results to create a second array indexed by id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment