Skip to content

Core\Db\Connection::execute

$connection->execute(
    string $sql,
    array<mixed> $params,
    {timeout?: Core\Time\Duration},
): Core\Db\Write

Runs one statement that changes the database, and says what it did.

Core\Db\Connection::execute is the method for an insert, an update, a delete or a create table. It returns a Core\Db\Write. That object says how many rows changed, and it gives the id the database made for a new row. A statement that reads rows belongs to Core\Db\Connection::query 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 write one row, change several rows with one statement, and name the values of a long statement.

Parameters

  • $sqlstringThe statement, with a ? or a :name for each value. Never write a value into the text. A tainted string 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. This is the same rule as in query.

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 an IOError. 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\Write. A Core\Db\Write with the number of affected rows as the server reported it, and the id that a RETURNING clause returned. Any rows the statement returned are read and discarded, so the connection is free again. Use query to keep rows.

Errors

  • LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, or a :name has no element. It is also thrown for an element that cannot be bound, such as an array or an object that is not an inList. 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's SQLSTATE and message.
  • IOErrorThe connection failed while the statement was running, or timeout passed before it finished. The connection cannot be used for the rest of the request.

Examples

The examples below run with this configuration file.

nvs.toml
# 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"]

Write a row and see what happened

<?nvs
// Shows the two things a write tells you: how many rows changed, and the id
// the database gave the new row.
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
var $written = $db->execute('insert into notes (text) values (?)', ['buy milk']);
// This prints `1 row written, id 1`.
echo $written->affected(), ' row written, id ', $written->lastId() ?? 0, "\n";
$db->close();
Output
1 row written, id 1

Change many rows with one statement

<?nvs
// Shows one update changing several rows. The count is the number of rows the
// database changed, and not the number of statements that ran.
var $db = Core\Db::connect('notes');
$db->execute('create table tasks (id integer primary key, done int not null)', []);
$db->execute('insert into tasks (done) values (?)', [0]);
$db->execute('insert into tasks (done) values (?)', [0]);
$db->execute('insert into tasks (done) values (?)', [1]);
var $changed = $db->execute('update tasks set done = ? where done = ?', [1, 0]);
// This prints `2 tasks were changed`.
echo $changed->affected(), " tasks were changed\n";
$db->close();
Output
2 tasks were changed

Name the values of a long statement

<?nvs
// Shows the values named instead of counted. A `:name` in the statement takes
// its value from the key of the same name. A long statement is easier to read
// this way, and the order of the keys does not matter.
var $db = Core\Db::connect('notes');
$db->execute('create table people (id integer primary key, name text not null, city text not null, age int not null)', []);
var $written = $db->execute(
'insert into people (name, city, age) values (:name, :city, :age)',
['city' => 'Bremen', 'name' => 'Ada', 'age' => 36],
);
// This prints `1 person written`.
echo $written->affected(), " person written\n";
$db->close();
Output
1 person written