View Full Version : Data Safe - SQL Injection

02-27-2008, 05:29 AM

This is an interesting question (in my humble opinion).

I am trying to create a forum in PHP. So there is a "Post a new Thread" link, clicking on which would open a textarea field for posting a message and a textbox for the "title".

Now, I dont want ppl to sql inject queries through the textarea or the textbox field.

So I have created this function for the same.

function dbsafe($data){
$data = str_replace('select','',$data);
$data = str_replace('alter','',$data);
$data = str_replace('delete','',$data);
$data = str_replace('replace','',$data);
return $data;

Now, though the above function would secure my db upto some extent but the only limitation I can see is my members/visitors will not be able to use the words "select","alter","delete","replace" in their threads even though they want use them (not for sql injection purpose).

So, I had to change my dbsafe function to the following:

function dbsafe($data){
$data = str_replace('tbl_members','',$data);
$data = str_replace('tbl_login','',$data);
$data = str_replace('tbl_details','',$data);
$data = str_replace('tbl_orders','',$data);
return $data;

ok, so now my function would now replace my database tables if the attacker intends to destroy or misuse them using any sql statements.

Now my question is that:

1) Which one of the above 2 functions is better you think?
2) Also, in my second function, is there a way the attacker would hamper my database without using my table names?

Please guide and help.

Need your opinion

Thanx so much in advance

02-27-2008, 06:25 AM
I would use neither. Have a look at mysql_real_escape_string (http://www.php.net/mysql_real_escape_string)().

02-27-2008, 07:31 AM
You can also use regex or htmlentities() (http://in2.php.net/htmlentities)

02-27-2008, 01:24 PM
You can also use regex or htmlentities() (http://in2.php.net/htmlentities)

No, not the same thing.

02-28-2008, 01:47 AM
You don't need all of these, (only mysql_real_escape_string,) but its good to know about these functions.

You can use these when inserting into a database:
mysql_real_escape_string (http://us2.php.net/mysql_real_escape_string)
strip_tags (http://us3.php.net/manual/en/function.strip-tags.php)
urldecode (http://us2.php.net/urldecode)

And these when displaying variables that have come out of a database:
stripslashes (http://us3.php.net/stripslashes)
htmlentities (http://us3.php.net/manual/en/function.htmlentities.php)

02-28-2008, 06:13 PM
Or just use prepared statements.