Jump to content

Query String Match


The Little Guy

Recommended Posts

I have this method:

protected function get_tables(){
preg_match_all("/(from|join)(.+?)(left|join|on|where|order|;|$)/i", $this->query, $select);
print_r($select);
$tables = $select[2];
foreach($tables as $k => $v){
	$tables[$k] = preg_replace("/( as.+| .+)/", '', trim($v));
}
return $tables;
}

 

the preg_match_all line is the one I am having issues with.

 

If this is the string I am trying to match:

 

select * from users u join ratings r on(u.id = r.user_id) where email = 'something'

 

the method is supposed to get all the tables used in the query string. The function works if I do a left join, but once I remove the left, it only matches the first table "users".

 

How can I get it to match both tables, and others if I add any?

Link to comment
Share on other sites

Try this expression.  It will even match tables that have the `tablename` characters.

 

(?:from|join)\s[`]?(\w+)[`]?

 

There are some syntax variations where this will not work, but I'm assuming this is a tool for your use and not a generic filter for all valid mysql syntax.  For example, there are variations where you can have a list of tables like (table1, table2, table3, etc) .  This also won't work right for something like

 

select * from tablea, tableb WHERE

Link to comment
Share on other sites

Here is my final result:

 

	protected function get_tables(){
	preg_match("/from(.+?)(where|$)/i", $this->query, $matches);
	$t1 = preg_split("/left|join|on.+?\(.+?\)|,/i", $matches[1]);
	$tables = array();
	foreach($t1 as $table){
		$tbls = preg_split("/as|\s/i", $table);
		$tbls = array_unique($tbls);
		$tbls2 = array();
		foreach ($tbls as $t){
			if(!empty($t))
				$tbls2[] = $t;
		}
		$tables[] = $tbls2;
	}
	$i = 0;
	$opt = array();
	foreach($tables as $tbl){
		if(!empty($tbl)){
			if(count($tbl) == 2){
				$opt[$tbl[1]] = str_replace('`', '', $tbl[0]);
			}else{
				$opt[$i] = str_replace('`', '', $tbl[0]);
			}
		}
		$i++;
	}
	return $opt;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.