Search code examples
phpmysqlutf-8sql-inserttext-formatting

proper way to format text to insert in database using php


I try to insert this information in Mysql database

$mytext = "this is a word in french d'origine francaise";

Then the PHP sql code:

$sql = "INSERT INTO tchapter (content) VALUES ('". $mytext ."')";

It will send me an error because i have a ' apostrophe character in the $mytext, in fact it will mix between the apostrophe '". $mytext ."' that exist in the $sql.

My question is what is the proper way to prepare the text to be entered in a database to prevent any type of error with the special character.

Also i should get back the text from the database as it appear before in the html page.


Solution

  • You can escape your string using the following function, prior to inserting in the database

    mysql_real_escape_string()