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
Databaseyourself. You write queries inquery/, configure the database inconfig.ini, and use the injected database service from your page logic. See https://www.php.gt/webengine/database/.
1. Install the library
composer require phpgt/database
2. Create a query directory
mkdir -p query/user
Create the file query/user/getById.sql:
select
id,
email
from
user
where
id = ?
limit 1
Calling user/getById later will resolve to this file.
3. Create a database connection
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.
4. Run the query
$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.
5. Build out the rest of the CRUD layer
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.