PHP - Storing Text in MySQL Database

Tom picture Tom · Apr 4, 2009 · Viewed 16k times · Source

I have a textbox on my website and I need to store whatever the user enters into my database, and retrieve it at a later time. I need to store it exactly as the user entered, including special characters, carriage returns, etc.

What process should I use in PHP to store this in my database field (which is a 'text' field)? Should I use PHP's html_encode or anything like that?

Thankyou.

Edit: I also need to store correct formatting i.e tabs and multiple spaces.

Answer

Calvin picture Calvin · Apr 4, 2009

Use mysql_real_escape_string():

$safetext = mysql_real_escape_string($_POST['text']);
$query = "INSERT INTO my_table (`my_field`) VALUES ('$safetext')";
mysql_query($query);

That should work.