Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between htmlspecialchars and mysqli_real_escape_string?

Tags:

php

mysql

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.

like image 452
Naeem Ul Wahhab Avatar asked Dec 07 '11 16:12

Naeem Ul Wahhab


People also ask

When should I use mysqli_real_escape_string?

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.

What is mysqli_real_escape_string used for?

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.

What is the difference between Addslashes () and htmlentities () in terms of functionality?

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.

Do I need mysqli_real_escape_string?

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.


1 Answers

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

like image 192
Shai Mishali Avatar answered Oct 28 '22 10:10

Shai Mishali