使用PHP从任何选择查询中提取表名

时间:2013-06-12 06:09:42

标签: php mysql

我尝试使用PHP从查询中获取所有表名,使用此函数我得到了除JOINS之外的所有条件和多个表,请帮助我使用相同的函数提取JOIN查询。

private function get_tables($query)
{
    $arr        =   explode("FROM", $query);
    $second     =   $arr[1];

    if($second==""){
        $arr    =   explode("from", $query);
        $second =   $arr[1];
    }

    $consts =   array('where','order', 'group', 'limit');
    $check=1;

    for($i=0;$i<count($consts); $i++)
    {
      if((stristr($second,$consts[$i])  !=  '')&&($check==1))
      {
          $where    =   explode($consts[$i],$second);
          if($check == 1)
          {
              $check=2;
              $tables= $where[0];
          }
      }
    }
    if($check == 1)
    {
      $tables= $arr[1]; 
    }
    $tab_arr    =   explode(',',$tables);
    $name_arr   =   array();

    foreach($tab_arr as $name)
    {
      if($name != '')
      { 
          $name =   trim($name);
          $narr =   explode(' ',$name);     
          $name_arr[]   =   $narr[0];
      }

    }
    $name_arr   =   array_unique($name_arr);
    return $name_arr;
}

2 个答案:

答案 0 :(得分:2)

也许您可以选择所有表格并在查询中找到

在mysql中:
一个数据库的SQL:

SHOW TABLES FROM {database_name};

所有数据库的SQL:

SELECT * FROM information_schema.tables 
WHERE TABLE_TYPE = 'BASE TABLE';

并在查询中找到:

$find_in_this_query = "your query";

$result = mysql_query("SHOW TABLES FROM sample_database;");

while ($row = mysql_fetch_row($result)) {
    if (strpos($find_in_this_query, $row[0]) !== false) {
        $found[] = $row[0];
    }
}

print_r($found);

答案 1 :(得分:1)

你不能用简单的正则表达式匹配解析SQL ...当表有别名时会发生什么?什么时候有子查询?交叉加入?工会? SQL语法非常丰富。

寻找一个SQL解析器。 e.g:

https://code.google.com/p/php-sql-parser/

相关问题