Page 1 of 1

PHP + MySQL Escaping Special Characters IMPORTANT..Please

Posted: Fri Jun 29, 2007 4:04 am
by captainoats
I have this variable which is a user input comes from a text box

$item=$_POST['item']; // sponge bob's & crabby# patty

I insert $item into the table without any problems.

Now I want to use it in a SELECT QUERY.

Lets say we are on on a different PHP page and I retrieved $item so I could use it for an SQL SELECT QUERY.


$tempQuery=mysql_query("SELECT * from itemtable where item_name= '$item' ");

Remember : $item contains an apostrophy(') ampersand(&) and pound sign(#)

How do I escape these characters so that my query will be executed properly. Now Im getting sql error coz of those special characters.

Im using PHP5 + MYSQL

I would like to know how to escape all the special characters.

In plain english hehehe...Im kinda new at this...THANKS

Posted: Fri Jun 29, 2007 4:27 am
by superdezign

Posted: Fri Jun 29, 2007 5:13 am
by John Cartwright
indeed, you should apply mysql_real_escape_string() or intval() (or sister function), depending if your expecting a string or integer value, to all incoming data, always.

now just how do i apply it?

Posted: Fri Jun 29, 2007 5:46 am
by captainoats
could you tell me how to use that function.. using my example $item


$tempQuery=mysql_query("SELECT * from ITEMTABLE where item_name='$item'");




hehe..thanks Id appreciate it if you guys help me. Im so stressed try everything @_@ I could really use some examples

Posted: Fri Jun 29, 2007 6:12 am
by mentor
Did you visit superdezign's provided PHP manual link?

This is how you can use this

Code: Select all

$tempQuery=mysql_query("SELECT * from ITEMTABLE where item_name='".mysql_real_escape_string($item)."'");

thanks

Posted: Fri Jun 29, 2007 7:47 am
by captainoats
thanks...let me try it out...tell you if it works...ciao!!!


BTW do i have to turn on magicquotes or anything?

Posted: Fri Jun 29, 2007 9:24 am
by patrikG
Try it out, if not your sever won't explode, your family will still know you and nobody will have stolen your car. The worst that can happen is that you get an error message... :roll:

Posted: Fri Jun 29, 2007 10:02 am
by volka
However ...the cat might get pregnant.

Working But some chars causes Problems

Posted: Fri Jun 29, 2007 6:01 pm
by captainoats
#
&
+

I found out that these characters are not solved by mysql_real_escape_string()

The rest are okay...

Any ideas how to escape these characters...? Thanks

Posted: Fri Jun 29, 2007 6:05 pm
by ReverendDexter
you could write a custom preg_match()...

http://us2.php.net/manual/en/function.preg-match.php

Posted: Fri Jun 29, 2007 7:00 pm
by superdezign
ReverendDexter wrote:you could write a custom preg_match()...

http://us2.php.net/manual/en/function.preg-match.php
... preg_replace().

Posted: Fri Jun 29, 2007 7:31 pm
by John Cartwright
why do you seen to escape + and & ?