-
-
Notifications
You must be signed in to change notification settings - Fork 3
Quick start guide
In this guide we will build a small SQLite-backed project, add one query collection, and run a query through GT\Database\Database.
Tip
In WebEngine we usually do not instantiate Database ourselves. We still write queries in query/, but the framework constructs the service for us. See https://www.php.gt/docs/webengine/database/.
composer require phpgt/databaseCreate a directory for the collection and add a query file:
query/
└── user/
└── getById.sql
query/user/getById.sql:
select
id,
email
from
user
where
id = ?
limit 1Later, calling user/getById 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);SQLite is a useful starting point because it keeps the example self-contained.
$db->executeSql(implode("\n", [
"create table user(",
"\tid integer primary key autoincrement,",
"\temail text not null",
")",
]));
$newId = $db->insert("user/insert", [
"email" => "dev@example.com",
]);If we are creating the table this way, we also need the matching insert query:
insert into user(email)
values(:email)Store that in query/user/insert.sql.
$user = $db->fetch("user/getById", (int)$newId);
echo $user?->getString("email");The first argument is the query name. The remaining arguments are the values to bind.
Once the first query is working, we usually fill out the rest of the collection in the same place:
query/user/insert.sqlquery/user/updateEmail.sqlquery/user/delete.sql
$rowsUpdated = $db->update("user/updateEmail", [
"id" => $newId,
"email" => "new@example.com",
]);
$rowsDeleted = $db->delete("user/delete", $newId);At that point we have the core shape of a phpgt/database project: one query directory, one connection, and one consistent way to execute database work.
Next, move on to Configuration and connections for the full Settings API.
PHP.GT/Database is a separately maintained component used by PHP.GT/WebEngine.