php mysql 在数据库的文本区域中存储换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12729524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php mysql storing line breaks in text area in database
提问by neeko
I have an input textarea and I would like to store the line breaks that a user makes in the text area in the database, so that it echoes the output text the same way as in the input text
我有一个输入 textarea 并且我想存储用户在数据库中的文本区域中所做的换行符,以便它以与输入文本相同的方式回显输出文本
eg:
例如:
Some text some text some text some text
new line some text some text new line
new line some text new line some text
this is my current upload script:
这是我当前的上传脚本:
$sql = "insert into people (price, contact, category, username, fname, lname, expire, filename) values (:price, :contact, :category, :user_id, :fname, :lname, now() + INTERVAL 1 MONTH, :imagename)";
$q = $conn->prepare($sql) or die("failed!");
$q->bindParam(':price', $price, PDO::PARAM_STR);
$q->bindParam(':contact', $contact, PDO::PARAM_STR);
$q->bindParam(':category', $category, PDO::PARAM_STR);
$q->bindParam(':user_id', $user_id, PDO::PARAM_STR);
$q->bindParam(':fname', $fname, PDO::PARAM_STR);
$q->bindParam(':lname', $lname, PDO::PARAM_STR);
$q->bindParam(':imagename', $imagename, PDO::PARAM_STR);
$q->execute();
回答by Micah Carrick
The line breaks in the text area are linebreak characters such as \n. These are not rendered in HTML and thus they won't show up if you simply echo the output. You can echo inside of a <textarea>or a <pre>tag or you can use the nl2br()to replace new lines with <br>tags so that it can be displayed as HTML.
文本区域中的换行符是换行符,例如\n. 这些不是在 HTML 中呈现的,因此如果您只是回显输出,它们将不会显示。您可以在 a<textarea>或 a<pre>标签内回显,或者您可以使用nl2br()用<br>标签替换新行,以便它可以显示为 HTML。
回答by martinwnet
You can escape the line breaks before storing by using mysql_real_escape_string
您可以在存储之前使用换行符转义 mysql_real_escape_string
Documentation here: http://php.net/manual/en/function.mysql-real-escape-string.php
文档在这里:http: //php.net/manual/en/function.mysql-real-escape-string.php
回答by Champ
you can also use javascript to break the text as \n to <br>by using replace
您还可以使用 javascript 来打破文本,如\n to <br>使用替换
str.replace("\n", "<br />","g");
回答by Melwin Kieffer
I had the same problem, and this is working now :
我遇到了同样的问题,现在正在工作:
$query = "UPDATE your_table
SET your_text_field = 'line 1'" . '\n' . "'line2'
WHERE your_id_field = " . $id . "';";

