Skip to content

Raw SQL and result sets

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

Most of the time, we should use query files. Occasionally, raw SQL is the right tool.

executeSql

$result = $db->executeSql(
	"select id, email from user where id > ?",
	[100]
);

We can also target a named connection:

$result = $db->executeSql("select 1", [], "analytics");

ResultSet behaviour

  • fetch() returns one Row or null
  • fetchAll() returns Row[]
  • asArray() returns array<int, array<string, string>>
  • affectedRows() returns the number of changed rows
  • lastInsertId() returns the insert id as a string
  • ResultSet is iterable and countable
$result = $db->executeSql("select id, email from user order by id");
foreach($result as $row) {
	echo $row->id, " ", $row->email, PHP_EOL;
}

Multi-statement query files

Query files may contain multiple SQL statements separated by semicolons. They are executed in order, and the final statement result is returned.

Clone this wiki locally