Skip to content

How to Use: Selecting Data

GrumpyCrouton edited this page Oct 19, 2022 · 3 revisions

Manual Select Queries

For any query, you could choose to use the run() method. This method returns a PDOStatement Object, so you can interact with it like native PDO.

$output = $db->run("SELECT * FROM users WHERE type=?", ['admin']);

This is essentially the same as running $pdo->query() or $pdo->prepare() (depending on if you send any values with it or not) and executing the query at the same time, then returning the PDOStatement Object from that. This means you can use one of PDO's many Fetch Modes from there.

Quick Queries

All of the following examples can accept at least 2 parameters. $query and $values. Some of them can accept more.

  • $query should be a parameterized query string using either anonymous placeholders or named placeholders.
  • $values can either be nothing, an empty array, or a key value pair of values to pass to the query. Should reflect the placeholders placed in the query, including position when using anonymous placeholders.

Example Output: all()

Fetch all of the results from the database into a multidimensional array. Read fetchAll() for additional parameters.

[
   {
      "uid":4,
      "name":"John Doe",
      "type":"Admin"
   },
   {
      "uid":2,
      "name":"John Baldwin",
      "type":"Admin"
   }
]

row()

Fetch a singular row from the database in a flat array. Read fetch() for additional parameters

{
  "uid":4,
  "name":"John Doe",
  "type":"Admin"
}

cell()

Fetch a single cell from the database. Doesn't support multiple rows. Read fetchColumn() for additional parameters

{
  "uid":4,
  "name":"John Doe",
  "type":"Admin"
}

column()

Fetch a single column from the database. Similar to cell(), except can have multiple rows. Functionally the same as PDO::FETCH_COLUMN

{2,4}

group()

Fetch an array with the values grouped by the value of the first column in the result set. The values in each set a set of arrays similar to the all() method. Functionally the same as PDO::FETCH_GROUP. The following example is based on the query SELECT gender, first_name, last_name FROM users

{
 "male": {
   ["first_name": "fname1", "last_name": "lname1"],
   ["first_name": "fname2", "last_name": "lname2"]
 },
 "female": {
   ["first_name": "fname3", "last_name": "lname3"],
   ["first_name": "fname4", "last_name": "lname4"]
 }
}

keypair()

Fetch an array of the result of the query as a key-value pair. The first column is the index, the second column is the value. Does not support duplicate indexes. Functionally the same as PDO::FETCH_COLUMN

{
 "column1": "value1",
 "column2": "value2"
}

keypairs()

Fetch an array of the result of the query as key-value pairs. The first column is the index, the value is an array of all of the values from the second column. The following example is based on the query SELECT gender, name FROM users

{
 "male": ["name1", "name2"],
 "female": ["name3", "name4"]
}