Skip to content

Raw SQL and result sets

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

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

executeSql

$result = $db->executeSql("lock table `users` in exclusive mode");

We can also target a named connection:

$result = $db->executeSql("select count(id) from user_page", [], "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 in the previously executed query.
  • lastInsertId() returns the last inserted id as a string, assuming auto increment was used.
  • ResultSet is iterable and countable.
$result = $db->fetchAll("user/getAllActive");
foreach($result as $row) {
	echo $row->getString("id"), ": ", $row->getString("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. A transaction is started before a query is executed, so if any queries within the same file fail, the transaction will be rolled back and no data will have changed.


PHP.GT/Database supports Database migrations to keep your schema tracked in version control.

Clone this wiki locally