Link to home
Start Free TrialLog in
Avatar of TecTaoMC
TecTaoMC

asked on

Confusion on useing Escape Special Characters

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.


Avatar of kevin_u
kevin_u
Flag of United States of America image

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.

Avatar of TecTaoMC
TecTaoMC

ASKER

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 ?
mysql_escape_string would be the best.
ASKER CERTIFIED SOLUTION
Avatar of TecTaoMC
TecTaoMC

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial