PDA

View Full Version : Escape quote(s)


progravix
9-13-07, 02:08 PM
I've written a simple PHP setup that adds, removes, and updated records in a mySQL database. The problem I am having is when I use a single quote (') in any of the html form fields. It gives the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's House of Fun', '', '', '', '', '', '', '', '', '', '', '', '', '' )' at line 2

I know I have to escape the quotes with a backslash, but this will eventually be in the hands of someone else, and I need it to addslash (which I guess is a PHP function). How in the heck can I do this? I've tried using online tutorial, but they all give errors. Others also warn about "magic_quotes". Does PowWeb have this on? I would assume not since my quotes are not getting escaped.

How can I fix this?

djwtwo
9-13-07, 04:34 PM
Anything you pass to MySQL should be passed through mysql_real_escape_string (http://us.php.net/manual/en/function.mysql-real-escape-string.php).

progravix
9-13-07, 05:00 PM
From what I understand, mysql_real_escape_string is used when making a query. What I need to do is escape ' and " before it's sent to the mySQL database. This way, it will display properly in query results and when updating the record where mySQL data is placed within a HTML form field.

I've found this to work, but there has got to be a way to "addslashes" to all POST data (otherwise this could get tedious):

Changed
$e_title=$_POST['title'];
to
$e_title=addslashes($_POST['title']);

YvetteKuhns
9-13-07, 06:13 PM
Did you try htmlentities (http://us.php.net/html_entities)?

HalfaBee
9-13-07, 06:35 PM
You use mysql_real_escape_string before doing the query.

So connect to the db and do this
$e_title=mysql_real_escape_string($_POST['title']);
mysql_query( ... );

You can loop thru all the $_POST in a foreach loop
e.g.

foreach( $_POST as $key => $data ) {
$clean_data[$key]=mysql_real_escape_string( $data );
}