Dave Moore said the following on 28/05/2005 18:44:
Hi All,
Can anybody point me to a FAQ or similar that describes what all this
stuff is about please?. I'm interfacing with a MySQL database if that's
relavent. I've read a couple of books which refer to stripslahes and
'escaping' but nothing really explains what these terms are and why these
are used. Why is 'escaping' (whatever that is) used?. What the hell is a
magic quote?. How is it different from a non-magic one?.
Imagine you're putting some data into a MySQL database. You might do
something like:
mysql_query("INSERT INTO table (name) VALUES ('$name')");
where $name is a string.
If $name was "John", the query string would become:
INSERT INTO table (name) VALUES ('John')
No problem there. But if $name was "Hell's Bells", then the string becomes:
INSERT INTO table (name) VALUES ('Hell's Bells')
Now, there's a mismatch in the number of single quotes, and this will
cause a MySQL error.
To get around this, one indicates a single-quote *within* a value string
using \' i.e backslash, single-quote. This is called "escaping" (one
escapes from the syntax processing that would normally occur).
All strings must be "escaped" before being put into an SQL query using
mysql_real_escape_string(), which does the conversion above (as well as
a few others). So your command would be:
mysql_query("INSERT INTO table (name) VALUES ('"
. mysql_real_escape_string($name) . "')");
Magic Quotes is something that seemed like a good idea back in the
earlier days of PHP. Basically, when Magic Quotes is turned on, all GET,
POST and COOKIE variables are automatically escaped ready for use in a
database query. This is to save lazy people time, so that they don't
have to call mysql_real_escape_string() each time.
However, they *will* have to call stripslashes() (which removes the
escaping from the string) whenever they want to use the string in a
normal context. So it's actually just a pain. If you have control of
your PHP configuration, turn magic-quotes off.
If not, you'll have to do something like at the top of your scripts:
if (get_magic_quotes_gpc())
{
foreach ($_GET as $key=>$value)
{
$_GET["key"] = stripslashes($value);
}
}
P.S. The best place to start on reading about anything PHP-related is
the online manual:
http://www.php.net/manual.
--
Oli