5

我想将 SQL 查询解析为数组。我无法弄清楚代码。

例子:

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

这个sql查询应该如下:

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

查询可能不同。

4

1 回答 1

15

使用 SQL 解析器。http://code.google.com/p/php-sql-parser/

从此示例中复制粘贴:

<?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);  

示例输出:

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
                )

        )

)
于 2012-06-15T13:47:10.330 回答