简体   繁体   中英

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 ie tabs and multiple spaces.

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.

You shouldn't html-encode the data when writing it to the datastorage - that way you could use your data also for something else (eg 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 eg).

You don't have to encode it in order to store it in a mysql.

Be sure you use a parameterized insert command, to avoid SQL injection.

The following should work:

if (get_magic_quotes_gpc()) {
  $content = stripslashes($content);
}
$content = mysql_real_escape_string($content);

If your column is utf8, you shouldn't have problems with special characters. Once you've formatted the content correctly, you can feed it to mysql using your standard insert methods.

To correctly store the user text in addition to the formatting, all you have to do is convert all the newlines to breaks using nl2br($inputtext) . Do this after filtering the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM