通过PHP添加WHERE,SELECT,ORDER BY等...就像链式SQL一样

问题描述:

I need to add WHERE, SELECT, ORDER BY etc...like a chain SQL by means of PHP. I use https://github.com/greenlion/PHP-SQL-Parser to spilt up the SQL in Array and then to form the SQL

i need a intermediate code. i can to add SELECT,WHERE, ORDER BY, ETC.. and i can test if exist in the table, fields, in array of PHPSQLParser.

Example:

$sSql = 'Select a, b, c from table1 inner join table2 on (table1.a = table2.a) where b = 900';

# Return array SQL
$aParser = new PHPSQLParser( $sSql );
$aParser = $aParser->parsed;

// I need to intermediate code add fields, conditions, etc. //

// Create the SQL through the array
$creator = new PHPSQLCreator( $this->aParser );

// Show SQL
echo $creator->created;

The package you are using is missing methods you need to work with the parsed query. If you write your own "query builder" package, you can use this package as a starting point so you don't have to write the code that parses the sql. Or better yet, you can use a different package altogether that has both query parsing and building included.

Here's one: https://github.com/jasny/dbquery-mysql

It can be used in the way you are asking:

<?php
    use Jasny\DB\MySQL\Query;

    $query = new Query("SELECT * FROM foo LEFT JOIN bar ON foo.bar_id = bar.id WHERE active = 1 LIMIT 25");
    if (isset($_GET['page'])) $query->page(3);

    $filter = isset($_POST['filter']) ? $_POST['filter'] : array(); // array('type' => 'bike', 'price between ? and ?' => array(10, 20))
    foreach ($filter as $field => $value) {
        $query->where($field, $value);
    }

    $result = $mysqli->query($query); // SELECT * FROM foo LEFT JOIN bar ON foo.bar_id = bar.id WHERE (active = 1) AND (`type` = "bike") AND (`price` between 10 and 20) LIMIT 25 OFFSET 50