A query builder for PDO MySQL and SQLite.
Download the latest phar from the releases page and include/use the lib in your project like any other PHP class:
require_once '/path/to/query-builder.phar';
$factory = new \Bloatless\QueryBuilder\QueryBuilderFactory($myConfig);
$queryBuilder = $factory->make();
You can install the library using composer:
composer require bloatless/query-builder
Clone or download the files from GitHub into your local project. You can than include/use the library within your project:
require_once '/path/to/src/QueryBuilderFactory.php';
$factory = new \Bloatless\QueryBuilder\QueryBuilderFactory($myConfig);
$queryBuilder = $factory->make();
This documentation explains the complete usage API of the Bloatless Query Builder.
You can define multiple database connections in your projects config.php
file.
$config = [
'db' => [
'connections' => [
'db1' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'db1',
'username' => 'root',
'password' => 'your-password',
'charset' => 'utf8', // Optional
'timezone' => 'Europe/Berlin', // Optional
],
'db2' => [
'driver' => 'sqlite',
'database' => '/path/to/sqlite.db',
]
// add additional connections here...
],
'default_connection' => 'db1',
]
];
The QueryBuilder factory needs to be initialized using a config array providing the connection credentials:
$db = new \Bloatless\QueryBuilder\QueryBuilder\Factory($config['db']);
Once initialized the factory can be used to provide query-builder objects for various database operations:
$selectQueryBuilder = $db->makeSelect();
$updateQueryBuilder = $db->makeUpdate();
$deleteQueryBuilder = $db->makeDelete();
$insertQueryBuilder = $db->makeInsert();
$rawQueryBuilder = $db->makeRaw();
With no arguments provided the default database connection is used. If you want to use a different connection you can pass the connection name as an argument.
$updateQueryBuilder = $db->makeUpdate('db2');
$rows = $db->makeSelect()->from('customers')->get();
Aliases can be used on table names as well as on column names.
$rows = $db->makeSelect()
->cols(['customer_id AS id', 'firstname', 'lastname'])
->from('customers AS c')
->get();
$rows = $db->makeSelect()
->cols(['customer_id', 'firstname', 'lastname'])
->from('customers')
->get();
$row = $db->makeSelect()
->from('customers')
->whereEquals('customer_id', 42)
->first();
$names = $db->makeSelect()
->from('customers')
->pluck('firstname');
Will fetch an array containing all first names of the customers
table.
You can specify a second column which will be used for the keys of the array:
$names = $db->makeSelect()
->from('customers')
->pluck('firstname', 'customer_id');
Will fetch an array of all first names using the customer_id
as array key.
$rowCount = $db->makeSelect()
->from('customers')
->count();
You can join tables using the join
, leftJoin
or rightJoin
methods. You can of course join multiple tables.
$rows = $db->makeSelect()
->from('customers')
->join('orders', 'customers.customer_id', '=', 'orders.customer_id')
->get();
$rows = $db->makeSelect()
->from('orders')
->groupBy('customer_id')
->get();
$rows = $db->makeSelect()
->from('customers')
->orderBy('firstname', 'desc')
->get();
$rows = $db->makeSelect()
->from('orders')
->having('amount', '>', 10)
->orHaving('cart_items', '>' 5)
->get();
$rows = $db->makeSelect()
->from('orders')
->limit(10)
->offset(20)
->get();
$rows = $db->makeSelect()
->distinct()
->from('orders')
->get();
$rows = $db->makeUpdate()
->table('customers')
->whereEquals('customer_id', 42)
->update([
'firstname' => 'Homer'
]);
$rows = $db->makeDelete()
->from('customers')
->whereEquals('customer_id', 42)
->delete();
You can use various where clauses on all select
, update
and delete
queries:
$rows = $db->makeSelect()
->from('customers')
->where('customer_id', '=', 42)
->where('customer_id', '>', 10)
->whereEquals('customer_id', 42)
->get();
->orWhere('customer_id', '>', 5)
->whereIn('customer_id', [1,2,3])
->whereNotIn('customer_id', [1,2,3])
->orWhereIn('customer_id', [1,2,3])
->orWhereNotIn('customer_id', [1,2,3])
->whereBetween('customer_id', 5, 10)
->orWhereBetween('customer_id', 5, 10)
->whereNull('customer_id')
->whereNotNull('customer_id')
->orWhereNull('customer_id')
->orWhereNotNull('customer_id')
->whereRaw('TIMESTAMPDIFF(HOUR, `time`, NOW()) <= 24')
->whereRaw('customer_id = :id', ['id' => 10])
->orWhereRaw('TIMESTAMPDIFF(HOUR, `time`, NOW()) <= 24')
$customerId = $db->makeInsert()
->into('customers')
->row([
'firstname' => 'Homer',
'lastname' => 'Simpson',
]);
When inserting a single row, the auto-increment value of the newly added row will be returned.
You can insert multiple rows at once using the rows
method:
$db->makeInsert()
->into('customers')
->rows([
[
'firstname' => 'Homer',
'lastname' => 'Simpson',
],
[
'firstname' => 'Marge',
'lastname' => 'Simpson',
],
]);
In case you need to fetch the id if the last insert manually you can use the getLastInsertId
method:
$id = $insertQueryBuilder->getLastInsertId();
There will always be some kind of queries you can not build using the methods of a query builder. In those cases you
can utilize the RawQueryBuilder
which allows you to execute raw queries to the database.
$rows = $db->makeRaw()
->prepare("SELECT * FROM `orders` WHERE `customer_id` = :id", [
'id' => 42,
])
->get();
$db->makeRaw()
->prepare("UPDATE `customers` SET `firstname` = :name WHERE `customer_id` = :id", [
'name' => 'Homer',
'id' => 42,
])
->run();
All query builders have a reset
method. This method can be used to clear all previously set values without the need
of creating a new QueryBuilder object.
$builder = $db->makeSelect()
->from('customers')
->whereEquals('customer_id', 42);
$builder->reset();
...
All query builders internally use PDO parameter binding to reduce the risk of injection attacks as much as possible. Additionally, table names as well as field names are quoted - so you don't have to worry about that. This works on simple table names or when using aliases. Nevertheless, you should always try to avoid using user input within sql statements!
MIT