Skip to content

Type safe getters

Greg Bowler edited this page Apr 2, 2026 · 4 revisions

This library includes a small set of helpers for common cases where a query returns one column and we already know the PHP type we want.

Single-value helpers

If a query returns one value, we can ask for that type directly:

  • fetchBool()
  • fetchString()
  • fetchInt()
  • fetchFloat()
  • fetchDateTime()
$username = $db->fetchString("user/getUsernameById", 105);
$score = $db->fetchFloat("score/calculateForUser", 8008);
$lastActivity = $db->fetchDateTime("user/getLatestActivity", 654);

This removes the usual "fetch row, then extract one column" boilerplate.

Multiple typed values

If the query still returns one column, but many rows, there are matching array helpers:

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

Typed access on Row

When we use fetch() or iterate over fetchAll(), each row also provides typed getters:

  • getString()
  • getInt()
  • getFloat()
  • getBool()
  • getDateTime()
  • get()
  • asArray()
$userRow = $db->fetch("user/getById", 105);

if($userRow) {
	echo $userRow->getString("email");
}

The getDateTime() helper accepts common database date strings as well as Unix timestamps.

Example: https://github.com/PhpGt/Database/blob/master/example/03-type-safe-getters.php


Next, move on to Database migrations to see how schema changes are tracked and applied safely.

Clone this wiki locally