> I'm confused about when I should escape single or double quotes.
Should
> all
> quotes be stored as \" or \' in a database as well?

Escape both, just use addslashes. The key here is that if you are
inserting a variable into a string (which is all a query is), then you
want to make sure that the contents of that variable don't unexpectedly
terminate the string.

> Regarding your suggestion above, is this what I should do? ...
> 
>     $name = "John AND fname = 'Mary'";
> 
>     $name = addslashes($name);
> 
>     // $name now holds: "John AND fname = \'Mary\'"
> 
> This forces MySQL to read \' as a character rather than as the
beginning
> of
> a variable value. So, in essence, this would produce a mySQL error
instead
> of executing the query, is that correct?

It depends on what you're doing with $name. Remember, you're just
creating a string that has to be logical when it's sent to MySQL

SELECT * FROM table WHERE name = '$name'
SELECT * FROM table WHERE name = "$name"

Either way you do it, you want to make sure that the contents of $name
don't have a quote that'll end the name string. 

If you have

$name = "John AND fname = 'Mary'";

and you don't escape quotes, then you have a query like

SELECT * FROM table WHERE name = 'John AND fname = 'Mary'
SELECT * FROM table WHERE name = "John AND fname = 'Mary'

Where the first one will cause an error and the second one will just not
match any rows, more than likely.

If you have

$name = "John' AND fname='Mary";

and you don't escape quotes, you'll get

SELECT * FROM table WHERE name = 'John' AND fname='Mary'
SELECT * FROM table WHERE name = "John' AND fname='Mary"

Where the first is a valid query and could return rows you didn't
normally intend for it to return. The second will probably not match any
rows again.

Now, don't think that double quotes are any safer. You can change $name
to use double quotes to manipulate the queries, too.

Bottom line is that you want to use addslashes() or magic_quotes_gpc()
on any variable you're going to insert into a query string. If you're
inserting a variable that should be a number, make sure it is one.

---John Holmes...




-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to