View Single Post

  #7 (permalink)  
Old 03-27-2008
Erwin Moller
 
Posts: n/a
Default Re: addslashes/mysql_real_escape_string

ndlarsen schreef:
> Lars Eighner wrote:
>
>> See the best practices example in the article on
>> mysql_real_escpae_string in
>> the manual. For portability you need to check for whether magic
>> quotes are
>> on and reverse them if they are. If portability is not a concern and
>> it is
>> your own machine, you can turn magic quotes off and save a few steps.

>
> I appreciate your reply. What baffles me is that is seems
> mysql_real_escape_string() is only run on the values one is using for a
> given database query, not the data inserted into the database. So there
> is no change made to the data in the database and there is no reason to
> run a function in order to strip the data of slashes? Is this so?
>
> Regards
>
> ndlarsen


Hi Larsen,

To answer that question, I ask you a question:

Consider a simple table:
tblPerson(
name text
)

Insert Joe in here:
INSERT into tblPerson (name) VALUES ('Joe');

Simple enough, right?

Now insert a name you received from a form on your webpage:
$name = $_POST["name"];
$SQL = "INSERT into tblPerson (name) VALUES ('".$name."');";

$someDB->Execute($SQL);

This is where things go wrong.
For starters, what happens in I post McPC's as a name?

Your SQL looks like:
INSERT into tblPerson (name) VALUES ('McPC's');

Which results in an error (mind the ').

You can also think up names that will delete all entries in your table
that way. (That trick is called SQL injection)

So that is where escaping comes into the picture.
What you need to insert McPC's is:
INSERT into tblPerson (name) VALUES ('McPC\'s');

That is something MySQL will handle as you intend.

Because MySQL has many more exploits/features besides the
stringterminator ('), you are wise to use mysql_real_escape_string()
which will find them all for you, and 'fix' them in such a way your
MySQL engine will understand the result.

You wrote:
What baffles me is that is seems mysql_real_escape_string() is only run
on the values one is using for a given database query, not the data
inserted into the database. So there is no change made to the data in
the database and there is no reason to run a function in order to strip
the data of slashes? Is this so?

The answer to that is that you need an insert query too to insert the
data in the database all the same. No matter if you are updating, or
inserting, or selecting: You ALWAYS must prepare for the worst.
An example:
Write a query that finds all persons in the above table that have the
name McPC's.

Hope this clearifies it a little.

Regards,
Erwin Moller
Reply With Quote