Core\Db\Connection::query
$connection->query(
string $sql,
array<mixed> $params,
{timeout?: Core\Time\Duration},
): Core\Db\Rows<Core\Db\Row>Runs one statement that reads rows, and returns all of them.
Core\Db\Connection::query is the method for a select. It returns a Core\Db\Rows object. A foreach over that object reads one row at a time. all() gives every row as an array, count() gives the number of rows, and first() gives the first row or null.
Every row is read into memory before the method returns. The connection is free again right after that, so the next statement can run while you are still reading the rows. When a result is too large to hold in memory, use Core\Db\Connection::queryEach instead.
A value never goes into the text of the statement. Write a ? for each value, or a :name for each, and pass the values as the second argument. The database keeps the statement and the values apart, so a value that looks like SQL stays a value.
The examples read the rows one at a time, read a result without a loop, and build a report from a statement whose values are named.
Parameters
$sqlstringThe statement, with a?or a:namefor each value. Never write a value into the text. Ataintedstring does not compile here, and no escape function can make one allowed.$paramsarray<mixed>The values to bind. Use list keys for?and string keys for:name, and never both in one array. ACore\Db::inListelement expands into several placeholders at its position. Nothing else expands.
Options
timeoutCore\Time\DurationoptionalHow long this statement may take. The limit covers the whole statement: the prepare, the execution and every row of the result. When the time passes, the statement stops with anIOError. The connection cannot be used again, because it stopped in the middle of a message. Without it, the statement waits as long as the server takes.
Return value
Returns Core\Db\Rows<Core\Db\Row>. A Core\Db\Rows<Core\Db\Row> with every row the statement returned, in the server's order. A statement that returns no rows, such as an update or a create table, gives an empty result. It is not an error.
Errors
LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, or a:namehas no element. It is also thrown for an element that cannot be bound, such as an array or an object that is not aninList. A statement already streaming on this connection throws it too.Core\Db\DbErrorThe server rejected the statement, for example for a syntax error, a constraint or a permission. The error has the server'sSQLSTATEand message. It is also thrown for a column type this driver cannot read yet.IOErrorThe connection failed while the statement was running, ortimeoutpassed before it finished. The connection cannot be used for the rest of the request.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\Db\Connection::query and Core\Db\Connection::queryEach create the column names once for each result. Every row uses the same names, so reading many rows is faster and allocates less memory. |
Examples
The examples below run with this configuration file.
# The `notes` database is kept in memory. It is deleted when the program ends.[db.notes]driver = "sqlite"path = ":memory:"
# The program may open the `notes` database.[capabilities.db]connect = ["notes"]Read the rows one at a time
<?nvs// Shows how to read the rows of a `select`, one row at a time.
var $db = Core\Db::connect('notes');$db->execute('create table notes (id integer primary key, text text not null)', []);$db->execute('insert into notes (text) values (?), (?), (?)', ['buy milk', 'call Ana', 'book train']);
// `query` returns every row of the statement. This prints the three notes,// one per line, with the id in front.foreach ($db->query('select id, text from notes order by id', []) as Core\Db\Row $row) { echo $row->int('id') ?? 0, ': ', $row->string('text') ?? '', "\n";}
$db->close();1: buy milk2: call Ana3: book trainRead a result without a loop
<?nvs// Shows the three ways to read a result without writing a loop over it: how// many rows there are, what the first row is, and every row as an array.
var $db = Core\Db::connect('notes');$db->execute('create table notes (id integer primary key, text text not null)', []);$db->execute('insert into notes (text) values (?), (?), (?)', ['buy milk', 'buy bread', 'call Ana']);
var $found = $db->query('select id, text from notes where text like ? order by id', ['buy%']);
// `count()` is the number of rows. This prints 2.echo $found->count(), "\n";
// `first()` is the first row, or `null` when the search found nothing.// This prints `buy milk`.echo $found->first()?->string('text') ?? 'nothing found', "\n";
// `all()` is every row as an array. The rows are already in memory, so// reading them a second time needs no second statement.foreach ($found->all() as Core\Db\Row $row) { echo '- ', $row->string('text') ?? '', "\n";}
$db->close();2buy milk- buy milk- buy breadBuild a report from named values
<?nvs// Shows a report a program really writes: one statement with named values,// and a total built from the rows it returns.
var $db = Core\Db::connect('notes');$db->execute('create table orders (id integer primary key, customer text not null, cents int not null, day text not null)', []);$db->execute('insert into orders (customer, cents, day) values (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?)', ['Ana', 1200, '2026-01-04', 'Ana', 800, '2026-01-19', 'Bo', 4500, '2026-01-22', 'Bo', 300, '2026-02-02']);
// A `:name` marks each value, and the same names are the keys of the second// argument. A long statement is easier to read this way than with `?`.var $rows = $db->query('select customer, sum(cents) as spent from orders where day >= :from and day <= :to group by customer order by spent desc', ['from' => '2026-01-01', 'to' => '2026-01-31']);
// This prints one line per customer, then the total of all of them. The order// of February is outside the two dates, so it is not counted.int $total = 0;foreach ($rows as Core\Db\Row $row) { int $spent = $row->int('spent') ?? 0; $total = $total + $spent; echo $row->string('customer') ?? '', ': ', $spent, "\n";}echo 'total: ', $total, "\n";
$db->close();Bo: 4500Ana: 2000total: 6500