Skip to content

Quick start guide

Greg Bowler edited this page Aug 31, 2026 · 8 revisions

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/.

1. Install the package

composer require phpgt/database

2. Create a query collection

Create 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 1

Later, calling user/getById will resolve to this file.

3. Create the connection settings

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.

4. Create a table and insert some data

$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.

5. Run the query

$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.

6. Add the rest of the collection

Once the first query is working, we usually fill out the rest of the collection in the same place:

  • query/user/insert.sql
  • query/user/updateEmail.sql
  • query/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.

Clone this wiki locally