2012-10-03 31 views
-1
<?php 
$str = "INSERT INTO `f_part` (lname,fname,email) VALUES ('tha','thia','[email protected]')"; 
?> 

任何人都可以帮我把这个字符串转换为数组转换SQL查询字符串数组格式

$result = array('table'=>'f_part', 
       'data'=>array('lname=>'tha','fname=>'thia','email'=>'[email protected]') 

      ) 
+0

[?你尝试过什么(http://www.whathaveyoutried.com) – h2ooooooo

+0

你的意思另一种方式?将查询字符串转换为数组没有意义吗? – JvdBerg

+3

StackOverflow!= [Google](http://www.google.com/search?q=php+sql+parser) – DaveRandom

回答

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] => 
       ) 

     ) 

) 
相关问题