@@ -56,14 +56,15 @@ Because it is **the most efficient way to deal with queries that can have a vari
5656Think about a typical datagrid with a bunch of filter (for instance a list of products filtered by name, company, price, ...).
5757If you have the very common idea to generate the SQL query using no PHP library, your code will look like this:
5858
59+ ###Without Magic-query
5960<div class =" alert " ><strong >You should not do this!</strong ></div >
6061
6162``` php
6263// People usually write queries like this:
6364$sql = "SELECT * FROM products p JOIN companies c ON p.company_id = c.id WHERE 1=1 ";
6465// They keep testing for parameters, and concatenating strings....
6566if (isset($params['name'])) {
66- $sql .= "AND p.name LIKE '".addslashes($params['name'])."%'";
67+ $sql .= "AND ( p.name LIKE '".addslashes($params['name'])."%' OR p.altname LIKE '".addslashes($params['name'])."%') ";
6768}
6869if (isset($params['company'])) {
6970 $sql .= "AND c.name LIKE '".addslashes($params['company'])."%'";
@@ -77,14 +78,26 @@ if (isset($params['country'])) {
7778Concatenating SQL queries is ** dangerous** (especially if you forget to protect parameters).
7879You can always use parametrized SQL queries, but you will still have to concatenate the filters.
7980
80- To avoid concatenating strings, frameworks and libraries have used different strategies. Building a full ORM (like
81+ ###With Magic-Query
82+
83+ ``` php
84+ // One query with all parameters
85+ $sql = "SELECT * FROM products p JOIN companies c ON p.company_id = c.id WHERE
86+ (p.name LIKE :name OR p.altname LIKE :name)
87+ AND c.name LIKE :company
88+ AND c.country LIKE :country";
89+
90+ $magicQuery = new MagicQuery();
91+ $sql = $magicQuery->build($sql, $params);
92+ ```
93+
94+ ###Other alternatives
95+
96+ To avoid concatenating strings, frameworks and libraries have used different strategies. Using a full ORM (like
8197Doctrine or Propel) is a good idea, but it makes writing complex queries even more complex. Other frameworks like
8298Zend are building queries using function calls. These are valid strategies, but you are no more typing SQL queries
8399directly, and let's face it, it is always useful to use a query directly.
84100
85- This is where Magic-query becomes helpful.
86-
87-
88101How does it work under the hood?
89102--------------------------------
90103
@@ -112,3 +125,10 @@ $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
112125
113126$magicQuery = new \Mouf\Database\MagicQuery($conn);
114127```
128+
129+ Any problem?
130+ ------------
131+
132+ As we said, a lot happen to your SQL query. In particular, it is parsed using a modified version
133+ of the php-sql-parser library. If you face any issues with a complex query, it is likely there is a bug
134+ in the parser. Please open [ an issue on Github] ( https://github.com/thecodingmachine/magic-query/issues ) and we'll try to fix it.
0 commit comments