-
-
Notifications
You must be signed in to change notification settings - Fork 4
Home
Greg Bowler edited this page Oct 3, 2025
·
5 revisions
When introducing database connections to your PHP applications, a structured approach to writing, maintaining and executing queries is required. The PHP.GT/Database project is intended to enhance your database query maintainability by introducing the following concepts:
- Automatic database migrations
- Encapsulation of queries using query collections
- Handling of named or sequential parameter binding
- Type-safe getters
This library organises SQL access through a consistent API. To execute an example query located at src/query/user/getById.sql
, the following pattern is used:
$userRow = $db->fetch("user/getById", 105);
Examples of CRUD operations:
// "fetchAll" method returns an iterable ResultSet of Row objects.
$bookResultSet = $db->fetchAll("shopitem/getItemsInCategory", "books");
foreach($bookResultSet as $bookRow) {
echo "Book title: ", $bookRow->getString("title"), PHP_EOL;
echo "Book price: £", ($bookRow->getFloat("price") + $bookRow->getFloat("vat")), PHP_EOL;
if($bookRow->offerEnds) {
echo "Item on offer until: ", $bookRow->getDateTime("offerEnds")->format("dS M Y");
}
}
// "Create" method always returns the last inserted ID:
$newCustomerId = $db->create("customer/new", [
"first_name" => "Marissa",
"last_name" => "Mayer",
"dob" => new DateTime("1975-05-30"),
]);
// "Update" or "delete" methods always return the number of affected rows:
$numberOfItemsAffected = $db->update("shop/item/increasePrice", [
"percent" => 12.5,
"max_increase" => 20.00,
]);
$numberOfDeletedReviews = $db->delete(
"remove/deleteOlderThan",
new DateTime("-6 months")
);
// Individual type-safe fields can be pulled from queries that return only one column:
$userName = $db->fetchString("user/getUsernameById", 105);
Read the Quick start guide to start learning by example.
PHP.GT/Database is a separately maintained component of PHP.GT/WebEngine.