php mysql storing line breaks in text area in database

笑着哭i 提交于 2019-12-21 20:24:43

问题


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

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();

回答1:


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.




回答2:


You can escape the line breaks before storing by using mysql_real_escape_string

Documentation here: http://php.net/manual/en/function.mysql-real-escape-string.php




回答3:


you can also use javascript to break the text as \n to <br> by using replace

str.replace("\n", "<br />","g");



回答4:


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 . "';";


来源:https://stackoverflow.com/questions/12729524/php-mysql-storing-line-breaks-in-text-area-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!