Confusion on useing Escape Special Characters

TecTaoMC
TecTaoMC used Ask the Experts™
on
It started when I was finding that data was not being put into fields of a mysql database.  Some information was being passed in text fields, text boxes from a rich text editor and others was not getting inserted.  On occasion, an entire form would not inserted.

In the refresh page I was using the standard $data=$_POST['data' ];

In reading I learned  that some data with special characters was causing the data entry problem.  In my reading I discovered there were a number of way to approach it.  But now I'm confused as to which is best to use and why.  Any quick overview would be helpful.  These are the what I'm confused over:

$data=mysql_real_escape_string($_POST['data']);

$data=mysqli_real_escape_string($_POST['data']);

$data=addslashes(htmlspecialchars($_POST['data']));

Thank you for any clarification.


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
mysql_real_escape_string is what you should use.  It "escapes" any special characters in the string, so it can be safely used as a string in an sql statement.

mysqli_real_escape_string is only used if you prefer to use the mysqli class.  There is no reason for you to use it if you're just starting out.

addslashes(htmlspecialchars( would sort of work too because special " and ' are escaped by addslashes, and special characters are turned into html entities.   However cr %0D and lf %0A are not converted using this method.  So multiline text areas would not be converted well.  These functions are really designed to make html happy, not sql.  In addition, displaying the values back on a site may require a reverse encoding.

mysql_real_escape_string is designed with mysql in mind, and thus handles a greater variety of circumstances.

Author

Commented:
Thank you Kevin,

That clarifies things.

I do use on occasion a php rich text editor that will add html characters such as <b> </b> , <i> </i>, paragraph tags, header tags and even font styles, size, color to text as it is added to the database.

Is is recommended to still use  mysql_escape_string  in this case or would the addslashes(htmlspecialchars) be best ?

Commented:
mysql_escape_string would be the best.
Commented:
great,
again, thanks kevin for your interest and comments...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial