Jump to content

Find the table from a sql query.


aliento

Recommended Posts

Hello,

I want to know which is the table in the sql SELECT query.

What i have done to take fields :

$temp_sql = strtolower($sql);
$pos = stripos($temp_sql, 'select');
$str = substr($temp_sql, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, 'where');
$temp_fields = substr($str_two, 0, $second_pos);
$fields = trim($temp_fields);

But for table i don't know what to do. After the table can end the string or can be a WHERE or ORDER .

Is there any way to take it.

Until now i use

$temp = explode(' ',$sql);

$table= $temp[3];

Thank you

Link to comment
https://forums.phpfreaks.com/topic/249017-find-the-table-from-a-sql-query/
Share on other sites

$temp_sql = strtolower($sql);
$pos = stripos($temp_sql, 'select');
$str = substr($temp_sql, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, 'where');
$temp_fields = substr($str_two, 0, $second_pos);
$fields = trim($temp_fields);

 

This problem occurs because your variable naming is not good :) I really do not mean it in a bad way. A variable name like $str or $str_two does not make sense at all, and hence the confusion.

 

I'd suggest, before continuing, make use of echo or print_r to see what each variable contains. Once you have received each variable's value, rename all your variables appropriately.

 

I hope it helps, I am also just a newbie around these parts, and I am trying to help, because I have received so much from this great  forum.

hey.. I got a PEAR library to parse the query I thing it may help you

 

http://pear.php.net/package/SQL_Parser

 

Simple Usage

 

 
require_once ‘SQL/Parser.php’;
$parser = new SQL_Parser();
$struct = $parser->parse("SELECT a,b,c FROM Foo");
print_r($struct);

 

SAMPLE OUTPUT 

Array
(
    [command] => select
    [column_tables] => Array
        (
            [0] =>
            [1] =>
            [2] =>
        )

    [column_names] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [column_aliases] => Array
        (
            [0] =>
            [1] =>
            [2] =>
        )

    [table_names] => Array
        (
            [0] => foo
        )

    [table_aliases] => Array
        (
            [0] =>
        )

    [table_join_clause] => Array
        (
            [0] =>
        )
)

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.