2012-06-15 63 views
2

我想解析一個SQL查詢到數組中。我無法弄清代碼。解析sql查詢PHP

實施例:

$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

http://code.google.com/p/php-sql-parser/ –

+2

HTTP://計算器.COM /問題/ 283087/PHP MySQL的-SQL語法分析器,插入和更新 – Kakawait

回答

10

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

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

輸出示例:

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 
       ) 

     ) 

)