-
-
Notifications
You must be signed in to change notification settings - Fork 3
Quick start guide
In this section we will build a tiny project that can run one query against a SQLite database.
Tip
In WebEngine, the same query layout is used, but you usually do not instantiate Database yourself. You write queries in query/, configure the database in config.ini, and use the injected database service from your page logic. See https://www.php.gt/webengine/database/.
composer require phpgt/databasemkdir -p query/user
Create the file query/user/getById.sql:
select
id,
email
from
user
where
id = ?
limit 1Calling user/getById later will resolve to this file.
use Gt\Database\Connection\Settings;
use Gt\Database\Database;
$settings = new Settings(
"query",
Settings::DRIVER_SQLITE,
"app.sqlite"
);
$db = new Database($settings);This example uses SQLite because it is simple to start with and does not need a running server.
$userRow = $db->fetch("user/getById", 105);
echo $userRow?->getString("email");The first argument is always the query name. The remaining arguments are the values to bind.
Once the first query works, it is natural to add more files:
query/user/insert.sqlquery/user/updateEmail.sqlquery/user/delete.sql
Then we can call them in the same style:
$newId = $db->insert("user/insert", [
"email" => "dev@example.com",
]);
$rowsUpdated = $db->update("user/updateEmail", [
"id" => $newId,
"email" => "new@example.com",
]);
$rowsDeleted = $db->delete("user/delete", $newId);At this point the basics are in place: query files, one connection, and a consistent PHP API.
Next, move on to Configuration and connections so we can see how the connection object is configured properly.
PHP.GT/Database is a separately maintained component that powers database features in PHP.GT/WebEngine.