Correct PHP method to store special chars in MySQL DB

Antonio Ciccia picture Antonio Ciccia · Apr 11, 2012 · Viewed 14.1k times · Source

Using PHP, what is the best way to store special characters (like the following) in a MSQUL database, to avoid injections.

« " ' é à ù

This is how I do it now:

$book_text=$_POST['book_text'];
$book_text=htmlentities($book_text, "ENT_QUOTES");
$query=//DB query to insert the text

Then:

$query=//DB query to select the text
$fetch=//The fetch of $book_text
$book_text=html_entity_decode($book_text);

This way, all my text is formatted in HTML entities. But I think this takes up a lot of database space. So, is there a better way?

Answer

Botanick picture Botanick · Apr 11, 2012

Use utf8 encoding to store these values.

To avoid injections use mysql_real_escape_string() (or prepared statements).

To protect from XSS use htmlspecialchars.