Repository navigation
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.
$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");-
fetch()returns oneRowornull. -
fetchAll()returnsRow[]. -
asArray()returnsarray<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. -
ResultSetis iterable and countable.
$result = $db->fetchAll("user/getAllActive");
foreach($result as $row) {
echo $row->getString("id"), ": ", $row->getString("email"), PHP_EOL;
}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.
PHP.GT/Database is a separately maintained component used by PHP.GT/WebEngine.