Error in sql statement

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
madu
Forum Commoner
Posts: 32
Joined: Sat Dec 25, 2010 3:19 am
Location: india

Error in sql statement

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Error in sql statement

Post by Weirdan »

But error came when print line6.
What the error was?
madu
Forum Commoner
Posts: 32
Joined: Sat Dec 25, 2010 3:19 am
Location: india

my error is

Post 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%'
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Error in sql statement

Post 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.
madu
Forum Commoner
Posts: 32
Joined: Sat Dec 25, 2010 3:19 am
Location: india

Re: Error in sql statement

Post by madu »

thank you.Got output.But is that function is remove from php6?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Error in sql statement

Post 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.
Post Reply