Skip to content

Type safe getters

Greg Bowler edited this page Mar 3, 2026 · 5 revisions

In this section, we will fetch single-column results as concrete PHP types.

Single-value helpers

Some queries are only expected to return a single value as their result. Rather than querying the database, fetching the row, and extracting the column from the row, this can be done in a single type-safe operation using the functions below:

  • fetchBool()
  • fetchString()
  • fetchInt()
  • fetchFloat()
  • fetchDateTime()

Example:

$username = $db->fetchString("user/getUserNameById", 42);
$score = $db->fetchFloat("score/calculateScoreForUser", 42);
$lastestActivity = $db->fetchDateTime("user/getLatestActivity");

Multi-value helpers

For queries that return just a single value, but will have multiple results in the query, the following type-safe fetch functions are defined for returning a typed array of values:

  • fetchAllBool()
  • fetchAllString()
  • fetchAllInt()
  • fetchAllFloat()
  • fetchAllDateTime()
$userIdArray = $db->fetchAllInt("user/getAllIds");

Type-safe access on Row

When we use fetch() or iterate fetchAll(), each row supports:

  • getString($column)
  • getInt($column)
  • getFloat($column)
  • getBool($column)
  • getDateTime($column)
  • get($column)
  • asArray()

The getDateTime() function accepts date strings and numeric unix timestamps from the database.

Example code: example/03-type-safe-getters.php


Next up, learn about working with raw SQL and result sets.

Clone this wiki locally