Search code examples
phpmysqlsql-injectionhtml-entitieshtml-encode

Correct PHP method to store special chars in MySQL DB


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?


Solution

  • Use utf8 encoding to store these values.

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

    To protect from XSS use htmlspecialchars.