Working with special characters (apostrophes) in MySQL and PHP

1k Views Asked by At

I am trying to solve a problem in a page that collects info from a form. In <head> we have:

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

Once connected to database there is a line:

mysql_query("SET NAMES utf8");

One of the fields that is inserted in variable $comments usually has apostrophes so we have a line:

$comments= addslashes($comments); 

before inserting it into database.

When we try to read out of database in another page we execute this line

stripslashes($row[$comments]);

When we had " we get a simple ? (question mark), it's actually stored like this in mySQL.

Other characters like simple apostrophe ' just becomes … in database and � or similar.

How do I get rid of these question mark characters and keep the original data?

1

There are 1 best solutions below

0
On

addslashes() is the wrong escaping function. You have to use mysql_real_escape_string(), because escaping is depending on the character set being used. And because of this you should better also use mysql_set_charset(), which should replace your SET NAMES utf8 query.

And alltogether, please note that the mysql extension is deprecated and will be removed from PHP. Use mysqli instead.

The reverse part is also wrong. There is no need to remove the escaping - it got removed when being "used" during the query. However, you must make sure that you properly encode all data you output to HTML.