将SQL查询字符串转换为数组格式

时间:2012-10-03 10:49:56

标签: php regex string multidimensional-array

<?php 
$str = "INSERT INTO `f_part` (lname,fname,email)  VALUES ('tha','thia','thia@gmail.com')";
?>

任何人都可以帮我将此字符串转换为数组

$result = array('table'=>'f_part',
                'data'=>array('lname=>'tha','fname=>'thia','email'=>'thia@gmail.com')

            )

1 个答案:

答案 0 :(得分:3)

您需要通过查找不同的MySQL关键字来分析查询,例如INSERT,SELECT,INTO,VALUES,FROM,WHERE等。但是,这可能会变得棘手和困难,因为您必须注意单引号,转义字符等。

我建议您使用http://code.google.com/p/php-sql-parser/。该课程已经完成了棘手的部分。它与你想要的输出并不完全相同,但它会为你提供类似的东西,甚至更多。

以下是一个示例查询:

SELECT STRAIGHT_JOIN a,b,c 
  from some_table an_alias
 WHERE d > 5;

样本输出:

Array
( 
    [OPTIONS] => Array
        (
            [0] => STRAIGHT_JOIN
        )       

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

            [1] => Array
                (
                    [expr_type] => colref
                    [base_expr] => b
                    [sub_tree] => 
                    [alias] => `b`
                )

            [2] => Array
                (
                    [expr_type] => colref
                    [base_expr] => c
                    [sub_tree] => 
                    [alias] => `c`
                )

        )

    [FROM] => Array
        (
            [0] => Array
                (
                    [table] => some_table
                    [alias] => an_alias
                    [join_type] => JOIN
                    [ref_type] => 
                    [ref_clause] => 
                    [base_expr] => 
                    [sub_tree] => 
                )

        )

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

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

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

        )

)