didslm / sql-builder
A flexible PHP package to build SQL queries using the builder pattern.
v1.1.1
2023-09-16 22:47 UTC
Requires
- php: ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.19
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^9.5
README
SQL Query Builder is a PHP package designed to help developers construct SQL queries, from the simplest to the most complex, using the builder pattern.
Features
- Simple and intuitive API.
- Supports various SQL operations including
SELECT
,INSERT
,UPDATE
, andDELETE
. - Extendable architecture allows for adding more custom query types.
- Strongly typed components like
Where
,Join
, andOrderBy
provide better IDE support and reduce runtime errors.
Installation
Using Composer:
composer require didslm/sql-builder
Usage
Simple SELECT query
<?php require 'vendor/autoload.php'; use Didslm\QueryBuilder\SelectQueryBuilder; $query = SelectQueryBuilder::from('users') ->select('*') ->where('age', 18) ->build(); echo $query; // Outputs: SELECT * FROM users WHERE age = 18
Complex Query
$query = SelectQueryBuilder::from('users') ->select('*') ->join('posts', 'users.id', 'posts.user_id') ->where('users.age', 18, '>') ->where('posts.published', true) ->build(); echo $query; // Outputs: SELECT * FROM users JOIN posts ON users.id = posts.user_id WHERE users.age > 18 AND posts.published = true
Grouped conditions
$sql = SelectBuilder::from('users') ->where('name', 'John') ->and('age', 18) ->and('email', 'selimi') ->or('name', 'test') ->and('email', 'selimi') ->build(); echo $sql; // Outputs: SELECT * FROM users WHERE (name = 'John' AND age = 18 AND email = 'selimi') OR (name = 'test' AND email = 'selimi')
Testing
After cloning the repository and installing the dependencies, you can run the tests with:
vendor/bin/phpunit
Contributing
Pull requests are welcome! For major changes, please open an issue first to discuss what you'd like to change.
Please make sure to update the tests as appropriate.