-
Notifications
You must be signed in to change notification settings - Fork 1
Home
phpgt/sqlbuilder gives us a structured way to write SQL in PHP without giving up control of the SQL itself.
Instead of concatenating fragments of query strings throughout application code, we can represent a query as a class, extend it when a new use case appears, or build one fluently at the point of use.
Note
In PHP.GT/WebEngine applications, this library is most commonly used alongside phpgt/database when writing PHP-backed query collections.
- Class-based
select,insert,update, anddeletequeries. - Fluent builders for common one-off query construction.
- Reusable condition objects for grouped
whereandhavingclauses. - Helper condition classes for equality and comparison expressions.
- Subqueries and nested query composition.
- Table-definition query classes for
create table,alter table, anddrop table. - Simple, portable SQL syntax generation.
- It does not execute SQL.
- It does not inspect your schema.
use GT\SqlBuilder\Query\SelectQuery;
class StudentSelect extends SelectQuery {
public function select():array {
return [
"id",
"name",
"dateOfBirth",
];
}
public function from():array {
return [
"student",
];
}
public function where():array {
return [
"deletedAt is null",
];
}
}class ActiveStudentSelect extends StudentSelect {
public function where():array {
return array_merge(parent::where(), [
"status = 'active'",
]);
}
}echo new ActiveStudentSelect();Output:
select
`id`,
`name`,
`dateOfBirth`
from
`student`
where
`deletedAt` is null
and
`status` = 'active'That prints a valid SQL query, but the important part is the shape of the code: the base query stays in one place, and the variation extends it instead of repeating it.
To see the two main ways of working with the library before we start building anything, continue with Overview.
PHP.GT/SqlBuilder is a separately maintained component of PHP.GT/WebEngine