如何在php中将文本插入数据库

Input string from text area

line1
line2 ‘
”line3″
<div>line4<div>

Wanted in database

line<br />1line2 '<br />"line3"<br />&lt;div&gt;line4&lt;div&gt;

I'm using this but it has some error. Nothing inserted to database from example i gave, when an input has a quotes.

$input = $_POST['textarea'];
$input = trim($input);
$input = htmlspecialchars($input);
$input = nl2br($input);
$input = mysql_real_escape_string($input);

Better way will be not use nl2br when you save into DB. Will be much better use nl2br when you will print textarea value on the page

echo nl2br($dataFromDB);

Well, I think that the error is caused by the type of your column in the data base !!! Is it type of text or varchar ???

Generally, try to get the data type as specific as you can. If your strings will never exceed some upper limit of characters, then go with VARCHAR because it will be a little more efficient. If you need more space, go with TEXT. If you aren't sure how much space your text will take up, you should probably go with TEXT; the performance difference isn't very large, and it's better to be future-proof than risk having to change it later when your requirements change.

VARCHAR you can set a limit for how many chars it will accept per record, text is (virtually) unlimited..

MySQL will internally convert TEXT to varchar while creating temporary tables. So it is better to use VARCHAR if possible.

It really depends on your data type.

If your field is fixed-length (e.g. a 32-character hash value), then use CHAR. This has better performance because every entry takes up the same space per row.

The standard limit for VARCHAR was 255 characters but I think it's been increased now. TEXT is pretty damn long and is generally only used for big content like a whole blog post, and comments if you don't want a limit.

With regard to size there is no (or very little) difference between VARCHAR and TEXT since they just store what they need to. CHAR fields will always take up their allotted length.

I hope it will help you, best regards.

you can use PHP fuctions

string urlencode ( string $str ) to encode the text and then insert into database

$input = urlencode ($input);

and string urldecode ( string $str ) to decode the text

$input = urldecode ($input);

try online fuction here