Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What is the best way to create higher level query language to create criteria filter in yii

I have database in mysql. On the php application I want to create a textarea and allow users to write a "query" to filter the data on the table.

I want to create a query parser for users to filter data by writing a query. For example:

name="John" AND (age > 20 OR status = 1)

Something like this. This is what users will type and press search button and the system creates sql query out of the "query" provided by user and return filtered results. In the example above, it will create sql query like this:

SELECT * FROM users WHERE name="John" AND (age>20 OR status=1)

I am thinking of parsing this query with regex and create sql from it. Is there any better approach?

like image 515
Jamol Avatar asked Jun 08 '15 16:06

Jamol


People also ask

What is high level query language?

High-Level MapReduce Query Languages (MapReduce-based HLQL) are built directly on the top of Hadoop MR to facilitate using MR as the low-level programming model [5]. They outline the absence of support that MR provides for complex dataflows and they provide explicit support for multiple data sources.

How to write SQL query in yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

What is Query Builder in yii2?

The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.

What is Query Builder in PHP?

Introduction. The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.


1 Answers

Due to the flexibility of SQL, and also for security, you'll want to use a lexer. This way you can allow for very complex queries, validate every field and value, and provide useful feedback on errors. I can think of two good options:

If the user input is relatively simple (e.g. no sub-selects) it shouldn't take long to define the sets of queries you want to support using a lexer already written in PHP, like Phlexy.

If you need more robust support for SQL, I would suggest Antlr because it already has various forms of SQL supported. The downside is PHP doesn't seem to be a supported target language at the moment, so integration will be more difficult.

like image 174
Matt S Avatar answered Sep 28 '22 20:09

Matt S