@@ -4,6 +4,26 @@ What is Magic-query?
4
4
Magic-query is a PHP library that helps you work with complex queries that require
5
5
a variable number of parameters.
6
6
7
+ How does it work?
8
+ -----------------
9
+
10
+ Easy! You write the query with all possible parameters.
11
+
12
+ ``` php
13
+ $sql = "SELECT * FROM users WHERE name LIKE :name AND country LIKE :country";
14
+
15
+ // Get a MagicQuery object.
16
+ $magicQuery = new MagicQuery();
17
+
18
+ // Let's pass only the "name" parameter
19
+ $result = $magicQuery->build($sql, [ "name" => "%John%" ]);
20
+ // $result = SELECT * FROM users WHERE name LIKE '%John'
21
+
22
+ // Let's pass no parameter at all!
23
+ $result2 = $magicQuery->build($sql, []);
24
+ // $result2 = SELECT * FROM users
25
+ ```
26
+
7
27
Why should I care?
8
28
------------------
9
29
@@ -39,37 +59,12 @@ directly, and let's face it, it is always useful to use a query directly.
39
59
40
60
This is where Magic-query becomes helpful.
41
61
42
- How does it work?
43
- -----------------
44
-
45
- Easy! You write the query with all possible parameters.
46
-
47
- ``` php
48
- $sql = "SELECT * FROM
49
- products p JOIN companies c
50
- ON p.company_id = c.id
51
- WHERE
52
- p.name LIKE :name
53
- AND c.name LIKE :company
54
- AND c.country LIKE :country";
55
-
56
- // Get a MagicQuery object.
57
- $magicQuery = new MagicQuery();
58
-
59
- // Here, we pass only the "name" parameter
60
- $generatedSql = $magicQuery->build($sql, [ "name" => "%John%" ]);
61
- // $generatedSql will not include the "c.name" filter!
62
-
63
- // Here we pass no parameters
64
- $generatedSql2 = $magicQuery->build($sql, []);
65
- // The WHERE statement will be completely removed!
66
- ```
67
62
68
63
How does it work under the hood?
69
64
--------------------------------
70
65
71
66
A lot happens to your SQL query. It is actually parsed (thanks to a modified
72
- version of the php-sql-parser library) and then changed into a tree.
73
- The magic happens on the tree where the node containing unused parameters
74
- are simply discarded. When it's done, the tree is changed back to SQL and
75
- "shazam!", your SQL query is purged of useless parameters!
67
+ version of the php-sql-parser library) and then changed into a tree.
68
+ The magic happens on the tree where the node containing unused parameters
69
+ are simply discarded. When it's done, the tree is changed back to SQL and
70
+ "shazam!", your SQL query is purged of useless parameters!
0 commit comments