Page 1 of 1

Error in sql statement

Posted: Fri Jan 28, 2011 2:43 am
by madu
i have stored my database table name into variable.The code is

Code: Select all

$w=$_GET['group'];
$sg=$_GET['gname'];

foreach($sg as $k => $v)
		{
			$sq="select * from $w where subg like %$v%";

			echo $sq;//line 4

			$res=mysql_query($sq) or die("Error in selection of sub group ". mysql_error());
		
			print_r($res); //line6
	
			echo "<br>";
	
		}
//i got correct query while i am printing(line 4).But error came when print line6.What is the problem.Help me.please

Re: Error in sql statement

Posted: Fri Jan 28, 2011 3:18 am
by Weirdan
But error came when print line6.
What the error was?

my error is

Posted: Fri Jan 28, 2011 3:21 am
by madu
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%college%'

Re: Error in sql statement

Posted: Fri Jan 28, 2011 3:27 am
by Weirdan
You have to put the argument for LIKE operator into quotes, like this:

Code: Select all

$sq = "select * from $w where subg like '%" . mysql_real_escape_string(str_replace(array('%', '_'), '', $v)) . "%'";
Note the single quotes before first percent sign and just before the string end.

mysql_real_escape_string() is there to protect you from SQL injections and str_replace are for LIKE metacharacters (that's optional)

Edit: You need to filter the $w variable though, otherwise you're still wide open for sql injections.

Re: Error in sql statement

Posted: Fri Jan 28, 2011 3:53 am
by madu
thank you.Got output.But is that function is remove from php6?

Re: Error in sql statement

Posted: Fri Jan 28, 2011 4:11 am
by Weirdan
madu wrote:thank you.Got output.But is that function is remove from php6?
There's no PHP6 and won't be in the near future.