Forum Moderators: coopster

Message Too Old, No Replies

Is this select safe from mysql injections?

         

smagdy

6:08 pm on Jan 11, 2007 (gmt 0)

10+ Year Member



Hello,

I am using MySQL and PHP and would like to know if this Select is safe from mysql injections or other kind of hacks cuz this is the main one in the site, the string in the where comes from text box

$text = text-box string;
i do this:

$text = htmlspecialchars($text,ENT_QUOTES, 'UTF-8');
$text = strip_tags($text);
$text = stripslashes($text);

mysql_query("SELECT field from table where `adtext` LIKE '%$text%'");

I know i should use mysql_real_escape_string but when i tried it using the below function it gave error so do i have to use it or its enough since there is 2 qutation around the text like this:
'% text %'

function quote_smart($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not a number or a numeric string
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}

$text = quote_smart($text);

Thanks in advance

eelixduppy

9:06 pm on Jan 11, 2007 (gmt 0)



You can just use this to prevent from SQL Injection:

$value = $_POST['textarea'];
if(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
}
$query = "SELECT * FROM table WHERE something = '".$value."'";

Good luck :)

HoboTraveler

11:05 am on Jan 16, 2007 (gmt 0)

10+ Year Member



@eelixduppy,

Do I use the same code when inserting variables into the DB?

and isin't

WHERE something = '".$value."'"

the same as

WHERE something = '$value'

What does the ". mean?

TIA

[edited by: HoboTraveler at 11:07 am (utc) on Jan. 16, 2007]

eelixduppy

12:05 pm on Jan 16, 2007 (gmt 0)



Yes, you would use something similar. If you know you do not have magic quotes enabled then you can omit this part:

if(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}

As for the second question

"...WHERE something = '".$value."'..."

is the same as

"...WHERE something = '$value'..."

As long as the second one is within double quotes. I just take variables out of strings like that because....well...I don't know. I guess it is just habit. :)

jatar_k

12:52 pm on Jan 16, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



quoting strings
[php.net...]

concatenation operator
[php.net...]

from the library
[webmasterworld.com...]