views:

50

answers:

2

Hello and thanks in advance.

I am retrieving data from the db. The data already went through mysql_real_escape_string when it was added to the db.

Once retrieved I am comparing it to a raw variable and depending upon the result I may be re-inserting the original db data back into the db into another, different, field.

My question is, do I have to use mysql_real_escape_string on this data I got from the database?

I think yes as the data could contain characters that need to be escaped and I think the backslashes are not stored in the db.

My code is:

if(isset($row['location_uri']) && $row['location_uri'] != $location_uri)
    {
    $session_previous_page = $row['previous_page_uri'];
    }
else
    {
    $session_previous_page = $row['location_uri'];
    }

Also, should I do anything with the db data before I compare it to the raw data, say from $_SERVER['REQUEST_URI']?

thanks for any help you can give.

+1  A: 

Yes. You answered your own question - because special characters are converted on read, you need to re-escape them on write.

I am not sure your exact question regarding $_SERVER['REQUEST_URI']. But if you should never trust these variables. So if you are comparing it in a DB query, at the least, I suggest escaping it.

Jason McCreary
thank you. I mean, I am comparing the $_Server['REQUEST_URI'] to the one stored in the database. So since it is coming out of the database as it is meant to appear, i.e. no backslashes, then I think it is ok to compare the db version with the $_Server['REQUEST_URI'] version.
k22k
If you are injecting the value into your query I still suggest escaping it. You should never trust anything - even values from `$_SERVER`.
Jason McCreary
oh I will do that of course. But I am worried that when I am comparing the 2 variables, there might be a problem that they don't match. I want to compare at php level the 2 variables, one from db and other from say $_Server.
k22k
+3  A: 

You should re-apply it. The escaping functions put in slashes, etc. so it is valid SQL syntax. Those slashes aren't actually stored in the database.

Patrick
thank you. I figured as much but wanted to be sure.
k22k