I read in a PHP book that it is a good practice to use htmlspecialchars
and mysqli_real_escape_string
in conditions when we handle user inputed data. What is the main difference between these two and where they are appropriate to be used? Please guide me.
You should use real_escape_string on any parameter you're mixing as a string literal into the sql statement. And only on those string literal values.
Definition and Usage. The mysqli_real_escape_string() function is used to escape characters in a string, making it legal to use in an SQL statement.
They are different tools for different purposes. mysqli_real_escape_string makes data safe for inserting into MySQL (but parametrized queries are better). addslashes assumes everything is 8bit. mysql_real_escape_string takes the character encoding into account when doing its encoding.
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.
These two functions are used for completely different things.
htmlspecialchars() converts special HTML characters into entities so that they can be outputted without problems. mysql_real_escape_string() escapes sensitive SQL characters so dynamic queries can be performed without the risk of SQL injection.
You could just as easily say that htmlspecialchars handles sensitive OUTPUT, while mysql_real_escape_string handles sensitive INPUT.
Shai
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