Search code examples
phpmysqltexthtml-encode

PHP - Storing Text in MySQL Database


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.


Solution

  • You shouldn't html-encode the data when writing it to the datastorage - that way you could use your data also for something else (e.g. emails, PDF documents and so on). As Assaf already said: it's mandatory to avoid SQL injections by escaping the input or using parameterized insert-queries.

    You should, no, let's say, must however html-encode your data when showing it on an HTML page! That will render dangerous HTML or Javascript code useless as the HTML-tags present in the data will not be recognized as HTML-tags by the browser any more.

    The process is a little more complicated when you'll allow the users to post data with HTML-tags inside. You then have to skip the output-encoding in favor of an input-sanitizing which can be arbitrary complex depending on your needs (allowed tags e.g.).