Possible Duplicate:
What does mysql_real_escape_string() do that addslashes() doesn't?
If you are trying to prevent sql injection, the first thing you would do is use mysql_real_escape_string. Is it possible to inject a database using addslashes()?
Definition and Usage The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (') double quote (")
You use mysqli_real_escape_string or any variation of it to make sure data form any user input field is properly escaped. For example, you have a form with a few inputs. You click submit and the data is sent as a request to your PHP script. In your script you insert into a database the values the user posted.
The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement.
Graham recently asked me: Do I still need to used mysqli_real_escape_string when used prepared statements in PHP? The simple answer is no. The way it used to work is that you would take form input data, put that into a variable, and inject that data into your MySQL query in order to add that data to the database.
addslashes is the rough equivalent of str_replace($str, "'", "\\'")
. You can bypass it trivially with any number of unicode sequences that evaluate down to '
in mysql, but look completely different to addslashes()
.
Mysql_real_escape_String()
on the other hand, uses the actual internal mysql escaping function, which knows exactly what to look for and fix to make it "safe" for mysql. What works for mysql may not work for another database, as each has slightly different escaping semantics and requirements, but if you're working with mysql, then the "real escape string" is the way to go.
This is what happens when you only add slashes in a language which understands unicode encodings (or mix up encodings while sending the query): http://bugs.mysql.com/bug.php?id=22243
Basically it's safer to know what the database expects in term of encoding - this way you won't end up escaping half of the character by accident, or leaving later part of a character unescaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With