66[ ![ GitHub license] ( https://img.shields.io/github/license/co0lc0der/simple-query-builder-php?style=flat-square )] ( https://github.com/co0lc0der/simple-query-builder-php/blob/main/LICENSE.md )
77![ Packagist PHP Version Support] ( https://img.shields.io/packagist/php-v/co0lc0der/simple-query-builder?color=8993be&style=flat-square )
88
9- This is a small easy-to-use PHP component for working with a database by PDO. It provides some public methods to compose SQL queries and manipulate data. Each SQL query is prepared and safe. PDO (see ` Connection ` class) fetches data to _ arrays_ by default. At present time the component supports MySQL and SQLite (file or memory).
9+ This is a small easy-to-use PHP component for working with a database by PDO. It provides some public methods to compose SQL queries and manipulate data. Each SQL query is prepared and safe. QueryBuilder fetches data to _ arrays_ by default. At present time the component supports MySQL and SQLite (file or memory).
1010
1111** PAY ATTENTION! v0.2 and v0.3+ are incompatible.**
1212
@@ -30,29 +30,7 @@ or add
3030"co0lc0der/simple-query-builder" : " *"
3131```
3232to the ` require section ` of your ` composer.json ` file.
33-
3433## How to use
35- ### Main public methods
36- - ` getSql() ` returns SQL query string which will be executed
37- - ` getParams() ` returns an array of parameters for a query
38- - ` getResult() ` returns query's results
39- - ` getCount() ` returns results' rows count
40- - ` hasError() ` returns ` true ` if an error is had
41- - ` getErrorMessage() ` returns an error message if an error is had
42- - ` setError($message) ` sets ` $error ` to ` true ` and ` $errorMessage `
43- - ` getFirst() ` returns the first item of results
44- - ` getLast() ` returns the last item of results
45- - ` reset() ` resets state to default values (except PDO property)
46- - ` all() ` executes SQL query and return all rows of result (` fetchAll() ` )
47- - ` one() ` executes SQL query and return the first row of result (` fetch() ` )
48- - ` column($col) ` executes SQL query and returns the needed column of result by its name, ` col ` is ` 'id' ` by default
49- - ` pluck($key, $col) ` executes SQL query and returns an array (the key (usually ID) and the needed column of result) by their names, ` key ` is ` id ` and ` col ` is ` '' ` by default
50- - ` go() ` this method is for non ` SELECT ` queries. it executes SQL query and return nothing (but returns the last inserted row ID for ` INSERT ` method)
51- - ` count() ` prepares a query with SQL ` COUNT(*) ` function and executes it
52- - ` exists() ` returns ` true ` if SQL query result has a row and ` false ` if it hasn't
53- - ` query($sql, $params[], $fetch_type) ` executes prepared ` $sql ` with ` $params ` . it can be used for custom queries
54- - 'SQL' methods are presented in [ Usage section] ( #usage-examples )
55-
5634### Edit ` config.php ` and set the parameters up. Choose DB driver, DB name etc
5735``` php
5836$config = require_once __DIR__ . '/config.php';
@@ -72,332 +50,46 @@ $query = new QueryBuilder(Connection::make($config['database'])); // $printError
7250$query = new QueryBuilder(Connection::make($config['database']), true)
7351```
7452### Usage examples
75- - Select all rows from a table
53+ #### Select all rows from a table
7654``` php
7755$results = $query->select('users')->all();
7856```
57+ Result query
7958``` sql
8059SELECT * FROM ` users` ;
8160```
82- - Select a row with a condition
83- ``` php
84- $results = $query->select('users')->where([['id', '=', 10]])->one();
85- // or since 0.3.4
86- $results = $query->select('users')->where([['id', 10]])->one();
87- ```
88- ``` sql
89- SELECT * FROM ` users` WHERE ` id` = 10 ;
90- ```
91- - Select rows with two conditions
61+ #### Select rows with two conditions
9262``` php
93- $results = $query->select('users')->where([
94- ['id', '>', 1],
95- 'and',
96- ['group_id', '=', 2],
97- ])->all();
98- // or since 0.3.4
9963$results = $query->select('users')->where([
10064 ['id', '>', 1],
10165 'and',
10266 ['group_id', 2],
10367])->all();
10468```
69+ Result query
10570``` sql
10671SELECT * FROM ` users` WHERE (` id` > 1 ) AND (` group_id` = 2 );
10772```
108- - Select a row with a ` LIKE ` and ` NOT LIKE ` condition
109- ``` php
110- $results = $query->select('users')->like(['name', '%John%'])->all();
111- // or
112- $results = $query->select('users')->where([['name', 'LIKE', '%John%']])->all();
113- // or since 0.3.6
114- $results = $query->select('users')->like('name', '%John%')->all();
115- ```
116- ``` sql
117- SELECT * FROM ` users` WHERE (` name` LIKE ' %John%' );
118- ```
119- ``` php
120- $results = $query->select('users')->notLike(['name', '%John%'])->all();
121- // or
122- $results = $query->select('users')->where([['name', 'NOT LIKE', '%John%']])->all();
123- // or since 0.3.6
124- $results = $query->select('users')->notLike('name', '%John%')->all();
125- ```
126- ``` sql
127- SELECT * FROM ` users` WHERE (` name` NOT LIKE ' %John%' );
128- ```
129- - Select a row with a ` IS NULL ` and ` IS NOT NULL ` condition (since 0.3.5)
130- ``` php
131- $results = $query->select('users')->isNull('phone')->all();
132- # or
133- $results = $query->select('users')->where([['phone', 'is null']])->all();
134- ```
135- ``` sql
136- SELECT * FROM ` users` WHERE (` phone` IS NULL );
137- ```
138- ``` php
139- $results = $query->select('customers')->isNotNull('address')->all();
140- # or
141- $results = $query->select('customers')->notNull('address')->all();
142- # or
143- $results = $query->select('customers')->where([['address', 'is not null']])->all();
144- ```
145- ``` sql
146- SELECT * FROM ` customers` WHERE (` address` IS NOT NULL );
147- ```
148- - Select rows with ` OFFSET ` and ` LIMIT `
149- ``` php
150- $results = $query->select('posts')
151- ->where([['user_id', '=', 3]])
152- ->offset(14)
153- ->limit(7)
154- ->all();
155- // or since 0.3.4
156- $results = $query->select('posts')
157- ->where([['user_id', 3]])
158- ->offset(14)
159- ->limit(7)
160- ->all();
161- ```
162- ``` sql
163- SELECT * FROM ` posts` WHERE (` user_id` = 3 ) OFFSET 14 LIMIT 7 ;
164- ```
165- - Select custom fields with additional SQL
166- 1 . ` COUNT() `
167- ``` php
168- $results = $query->select('users', ['counter' => 'COUNT(*)'])->one();
169- // or
170- $results = $query->count('users')->one();
171- ```
172- ``` sql
173- SELECT COUNT (* ) AS ` counter` FROM ` users` ;
174- ```
175- 2 . ` ORDER BY `
176- ``` php
177- $results = $query->select(['b' => 'branches'], ['b.id', 'b.name'])
178- ->where([['b.id', '>', 1], 'and', ['b.parent_id', '=', 1]])
179- ->orderBy('b.id', 'desc')
180- ->all();
181- // or since 0.3.4
182- $results = $query->select(['b' => 'branches'], ['b.id', 'b.name'])
183- ->where([['b.id', '>', 1], 'and', ['b.parent_id', 1]])
184- ->orderBy('b.id desc')
185- ->all();
186- ```
187- ``` sql
188- SELECT ` b` .` id` , ` b` .` name` FROM ` branches` AS ` b`
189- WHERE (` b` .` id` > 1 ) AND (` b` .` parent_id` = 1 )
190- ORDER BY ` b` .` id` DESC ;
191- ```
192- 3 . ` GROUP BY ` and ` HAVING `
193- ``` php
194- $results = $query->select('posts', ['id', 'category', 'title'])
195- ->where([['views', '>=', 1000]])
196- ->groupBy('category')
197- ->all();
198- ```
199- ``` sql
200- SELECT ` id` , ` category` , ` title` FROM ` posts`
201- WHERE (` views` >= 1000 ) GROUP BY ` category` ;
202- ```
203- ``` php
204- $groups = $query->select('orders', ['month_num' => 'MONTH(`created_at`)', 'total' => 'SUM(`total`)'])
205- ->where([['YEAR(`created_at`)', '=', 2020]])
206- ->groupBy('month_num')
207- ->having([['total', '=', 20000]])
208- ->all();
209- // or since 0.3.4
210- $groups = $query->select('orders', ['month_num' => 'MONTH(`created_at`)', 'total' => 'SUM(`total`)'])
211- ->where([['YEAR(`created_at`)', 2020]])
212- ->groupBy('month_num')
213- ->having([['total', 20000]])
214- ->all();
215- ```
216- ``` sql
217- SELECT MONTH(` created_at` ) AS ` month_num` , SUM (` total` ) AS ` total`
218- FROM ` orders` WHERE (YEAR(` created_at` ) = 2020 )
219- GROUP BY ` month_num` HAVING (` total` = 20000 );
220- ```
221- 4 . ` JOIN ` . Supports ` INNER ` , ` LEFT OUTER ` , ` RIGHT OUTER ` , ` FULL OUTER ` and ` CROSS ` joins (` INNER ` is by default)
222- ``` php
223- $results = $query->select(['u' => 'users'], [
224- 'u.id',
225- 'u.email',
226- 'u.username',
227- 'perms' => 'groups.permissions'
228- ])
229- ->join('groups', ['u.group_id', 'groups.id'])
230- ->limit(5)
231- ->all();
232- ```
233- ``` sql
234- SELECT ` u` .` id` , ` u` .` email` , ` u` .` username` , ` groups` .` permissions` AS ` perms`
235- FROM ` users` AS ` u`
236- INNER JOIN ` groups` ON ` u` .` group_id` = ` groups` .` id`
237- LIMIT 5 ;
238- ```
239- ``` php
240- $results = $query->select(['cp' => 'cabs_printers'], [
241- 'cp.id',
242- 'cp.cab_id',
243- 'cab_name' => 'cb.name',
244- 'cp.printer_id',
245- 'printer_name' => 'p.name',
246- 'cartridge_type' => 'c.name',
247- 'cp.comment'
248- ])
249- ->join(['cb' => 'cabs'], ['cp.cab_id', 'cb.id'])
250- ->join(['p' => 'printer_models'], ['cp.printer_id', 'p.id'])
251- ->join(['c' => 'cartridge_types'], 'p.cartridge_id=c.id')
252- ->where([['cp.cab_id', 'in', [11, 12, 13]], 'or', ['cp.cab_id', '=', 5], 'and', ['p.id', '>', 'c.id']])
253- ->all();
254- ```
255- ``` sql
256- SELECT ` cp` .` id` , ` cp` .` cab_id` , ` cb` .` name` AS ` cab_name` , ` cp` .` printer_id` ,
257- ` p` .` name` AS ` printer_name` , ` c` .` name` AS ` cartridge_type` , ` cp` .` comment`
258- FROM ` cabs_printers` AS ` cp`
259- INNER JOIN ` cabs` AS ` cb` ON ` cp` .` cab_id` = ` cb` .` id`
260- INNER JOIN ` printer_models` AS ` p` ON ` cp` .` printer_id` = ` p` .` id`
261- INNER JOIN ` cartridge_types` AS ` c` ON p .cartridge_id = c .id
262- WHERE (` cp` .` cab_id` IN (11 ,12 ,13 )) OR (` cp` .` cab_id` = 5 ) AND (` p` .` id` > ` c` .` id` )
263- ```
264- ``` php
265- // or since 0.3.4
266- $results = $query->select(['cp' => 'cabs_printers'], [
267- 'cp.id',
268- 'cp.cab_id',
269- 'cab_name' => 'cb.name',
270- 'cp.printer_id',
271- 'cartridge_id' => 'c.id',
272- 'printer_name' => 'p.name',
273- 'cartridge_type' => 'c.name',
274- 'cp.comment'
275- ])
276- ->join(['cb' => 'cabs'], ['cp.cab_id', 'cb.id'])
277- ->join(['p' => 'printer_models'], ['cp.printer_id', 'p.id'])
278- ->join(['c' => 'cartridge_types'], ['p.cartridge_id', 'c.id'])
279- ->groupBy(['cp.printer_id', 'cartridge_id'])
280- ->orderBy(['cp.cab_id', 'cp.printer_id desc'])
281- ->all();
282- ```
283- ``` sql
284- SELECT ` cp` .` id` , ` cp` .` cab_id` , ` cb` .` name` AS ` cab_name` , ` cp` .` printer_id` , ` c` .` id` AS ` cartridge_id` ,
285- ` p` .` name` AS ` printer_name` , ` c` .` name` AS ` cartridge_type` , ` cp` .` comment`
286- FROM ` cabs_printers` AS ` cp`
287- INNER JOIN ` cabs` AS ` cb` ON ` cp` .` cab_id` = ` cb` .` id`
288- INNER JOIN ` printer_models` AS ` p` ON ` cp` .` printer_id` = ` p` .` id`
289- INNER JOIN ` cartridge_types` AS ` c` ON ` p` .` cartridge_id` = ` c` .` id`
290- GROUP BY ` cp` .` printer_id` , ` cartridge_id`
291- ORDER BY ` cp` .` cab_id` ASC , ` cp` .` printer_id` DESC ;
292- ```
293- - Insert a row
294- ``` php
295- $new_id = $query->insert('groups', [
296- 'name' => 'Moderator',
297- 'permissions' => 'moderator'
298- ])->go();
299- ```
300- ``` sql
301- INSERT INTO ` groups` (` name` , ` permissions` ) VALUES (' Moderator' , ' moderator' );
302- ```
303- - Insert many rows
304- ``` php
305- $query->insert('groups', [
306- ['name', 'role'],
307- ['Moderator', 'moderator'],
308- ['Moderator2', 'moderator'],
309- ['User', 'user'],
310- ['User2', 'user'],
311- ])->go();
312- ```
313- ``` sql
314- INSERT INTO ` groups` (` name` , ` role` )
315- VALUES (' Moderator' , ' moderator' ),
316- (' Moderator2' , ' moderator' ),
317- (' User' , ' user' ),
318- (' User2' , ' user' );
319- ```
320- - Update a row
321- ``` php
322- $query->update('users', [
323- 'username' => 'John Doe',
324- 'status' => 'new status'
325- ])
326- ->where([['id', '=', 7]])
327- ->limit()
328- ->go();
329- // or since 0.3.4
330- $query->update('users', [
331- 'username' => 'John Doe',
332- 'status' => 'new status'
333- ])
334- ->where([['id', 7]])
335- ->limit()
336- ->go();
337- ```
338- ``` sql
339- UPDATE ` users` SET ` username` = ' John Doe' , ` status` = ' new status'
340- WHERE ` id` = 7 LIMIT 1 ;
341- ```
342- - Update rows
73+ #### Update a row
34374``` php
34475$query->update('posts', ['status' => 'published'])
34576 ->where([['YEAR(`updated_at`)', '>', 2020]])
34677 ->go();
34778```
79+ Result query
34880``` sql
34981UPDATE ` posts` SET ` status` = ' published'
35082WHERE (YEAR(` updated_at` ) > 2020 );
35183```
352- - Delete a row
353- ``` php
354- $query->delete('users')
355- ->where([['name', '=', 'John']])
356- ->limit()
357- ->go();
358- // or since 0.3.4
359- $query->delete('users')
360- ->where([['name', 'John']])
361- ->limit()
362- ->go();
363- ```
364- ``` sql
365- DELETE FROM ` users` WHERE ` name` = ' John' LIMIT 1 ;
366- ```
367- - Delete rows
368- ``` php
369- $query->delete('comments')
370- ->where([['user_id', '=', 10]])
371- ->go();
372- // or since 0.3.4
373- $query->delete('comments')
374- ->where([['user_id', 10]])
375- ->go();
376- ```
377- ``` sql
378- DELETE FROM ` comments` WHERE ` user_id` = 10 ;
379- ```
380- - Truncate a table
84+ More examples you can find in [ documentation] ( https://github.com/co0lc0der/simple-query-builder-php/blob/main/docs/index.md ) or tests.
38185
382- This method will be moved to another class
383- ``` php
384- $query->truncate('users')->go();
385- ```
386- ``` sql
387- TRUNCATE TABLE ` users` ;
388- ```
389- - Drop a table
390-
391- This method will be moved to another class
392- ``` php
393- $query->drop('temporary')->go(); // $add_exists = true
394- ```
395- ``` sql
396- DROP TABLE IF EXISTS ` temporary` ;
397- ```
398- ``` php
399- $query->drop('temp', false)->go(); // $add_exists = false
400- ```
401- ``` sql
402- DROP TABLE ` temp` ;
403- ```
86+ ## ToDo
87+ I'm going to add the next features into future versions
88+ - write more unit testes
89+ - add subqueries for QueryBuilder
90+ - add ` BETWEEN `
91+ - add ` WHERE EXISTS `
92+ - add TableBuilder class (for beginning ` CREATE TABLE ` , move ` $query->drop() ` and ` $query->truncate() ` into it)
93+ - add PostgreSQL support
94+ - add ` WITH `
95+ - and probably something more
0 commit comments