Skip to content

Page through database rows

A table can have more rows than one page should show. This program reads one page of three rows.

<?nvs
// This program reads database rows one page at a time.
class Guests
{
// Returns the names on page `$page`. Each page has `$size` rows, and the first page is 1.
public static function page(Core\Db\Connection $db, uint $page, uint $size): array<tainted string>
{
array<tainted string> $names = [];
// `limit` is the number of rows, and `offset` is the number of rows to skip.
var $rows = $db->query('select name from guests order by id limit ? offset ?', [$size, ($page - 1) * $size]);
foreach ($rows as Core\Db\Row $row) {
$names[] = $row->string('name') ?? '';
}
return $names;
}
}
// `connect` opens the database that `nvs.toml` names `guests`.
var $db = Core\Db::connect('guests');
$db->execute('create table guests (id integer primary key, name text not null)', []);
array<string> $guests = ['Ada', 'Bo', 'Cem', 'Dana', 'Eli', 'Fay', 'Gus'];
foreach ($guests as string $guest) {
$db->execute('insert into guests (name) values (?)', [$guest]);
}
// There are seven guests. Page 2 has the guests 4 to 6, so this prints Dana, Eli and Fay.
foreach (Guests::page($db, 2, 3) as tainted string $name) {
echo $name, "\n";
}
$db->close();
Output
Dana
Eli
Fay

The nvs.toml in the same folder names the database and allows the program to open it:

[db.guests]
driver = "sqlite"
path = ":memory:"
[capabilities.db]
connect = ["guests"]

limit ? offset ? in the query reads $size rows after skipping the rows of the pages before. Each ? is replaced by a value from the array, in the same order. Never put a value into the SQL text yourself.

The query has order by id. Without an order, the database may return the rows in a different order each time, and a row can appear on two pages.

Read Core\Db for how to connect to a database.