Parsing sql query PHP [closed]

2019-01-26 16:15发布

I want to parse a SQL query into an array. I could not figure out the code.

Example:

$sql_query = "SELECT id, login, pass FROM users WHERE id=3, login=faforty ORDER DESC LIMIT 3"';

and this sql query should be as follows:

$data = array();
$data['select'] = array('id', 'login', 'pass');
$data['from'] = array('id' => 3, 'login' => 'faforty');
$data['order'] = 'desc';
$data['limit'] = 3;

Query may be different.

标签: php sql parsing
1条回答
别忘想泡老子
2楼-- · 2019-01-26 16:45

Use an SQL parser. http://code.google.com/p/php-sql-parser/

Copy paste from this example:

<?php
  require_once('php-sql-parser.php');
  $parser=new PHPSQLParser('SELECT a FROM some_table an_alias WHERE d > 5;', true);

  print_r($parser->parsed);  

Example output:

Array
(
    [SELECT] => Array
        (
            [0] => Array
                (
                    [expr_type] => colref
                    [alias] => 
                    [base_expr] => a
                    [sub_tree] => 
                    [position] => 8
                )

        )

    [FROM] => Array
        (
            [0] => Array
                (
                    [expr_type] => table
                    [table] => some_table
                    [alias] => Array
                        (
                            [as] => 
                            [name] => an_alias
                            [base_expr] => an_alias
                            [position] => 29
                        )

                    [join_type] => JOIN
                    [ref_type] => 
                    [ref_clause] => 
                    [base_expr] => some_table an_alias
                    [sub_tree] => 
                    [position] => 18
                )

        )

    [WHERE] => Array
        (
            [0] => Array
                (
                    [expr_type] => colref
                    [base_expr] => d
                    [sub_tree] => 
                    [position] => 45
                )

            [1] => Array
                (
                    [expr_type] => operator
                    [base_expr] => >
                    [sub_tree] => 
                    [position] => 47
                )

            [2] => Array
                (
                    [expr_type] => const
                    [base_expr] => 5
                    [sub_tree] => 
                    [position] => 49
                )

        )

)
查看更多
登录 后发表回答