kekos / query-builder
Small SQL query builder
Installs: 7 366
Dependents: 1
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^10.5
README
A fork of Muhammad Usman's Pixie, a lightweight query builder for PHP. This library only supports a subset of Pixie's fetures:
- Nested criterias (
WHERE
,HAVING
andON
for joins) - Raw queries
Query Builder is not able to open database connections or execute the built queries.
Install
You can install Query Builder via Composer:
composer require kekos/query-builder
API
Start by configure Query Builder with an adapter:
QueryBuilder::setAdapter(new MySqlAdapter());
The adapter sets the correct sanitizer character.
At this moment MySqlAdapter
is provided with the library.
All builders have a toSql()
method, which returns the SQL query and all
parameters to be bound to the query, to be used with prepared statements.
Select
$result = QueryBuilder::select(['user', 'u']) ->columns(['u.id', 'uname' => 'username']) ->joinOn(['user_permission', 'p'], 'p.user_id', 'u.id') ->limit(5, 0) ->groupby(['u.id']) ->orderby(['username ASC', 'firstname ASC']) ->where('firstname', '=', 'Christoffer') ->whereNot('u.id', 'IN', array(2)) ->toSql();
$result
will be an object of type QueryBuilder\QueryBuilders\Raw
.
Nested where
or having
$result = QueryBuilder::select('user') ->orderby('id') ->where(function($qb) { $qb->where('name', 'LIKE', '%chris%') ->whereOr('username', 'LIKE', '%chris%'); }) ->where('active', '=', 1) ->toSql();
Insert
$result = QueryBuilder::insert('user') ->values([ 'username' => 'Kekos', 'firstname' => 'Christoffer' ]) ->toSql();
Update
$result = QueryBuilder::update('user') ->set([ 'username' => 'new_username', 'firstname' => 'New firstname' ]) ->where('id', '=', 2) ->toSql();
Delete
$result = QueryBuilder::delete('user') ->where('id', '=', 2) ->toSql();
Bugs and improvements
Report bugs in GitHub issues or feel free to make a pull request :-)
License
MIT