How to Save User-Entered Line Breaks from a Textarea to a Database

How do I preserve line breaks when getting text from a textarea?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

document.getElementById('post-button').addEventListener('click', function () {  var post = document.createElement('p');  var postText = document.getElementById('post-text').value;  post.append(postText);  var card = document.createElement('div');  card.append(post);  var cardStack = document.getElementById('card-stack');  cardStack.prepend(card);});
#card-stack p {  background: #ddd;  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */}textarea {  width: 100%;}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:
Tuesday practice @ 5th floor (8pm - 11 pm)
Thursday practice @ 5th floor (8pm - 11 pm)
Sunday practice @ (9pm - 12 am)</textarea><br><input type="button" id="post-button" value="Post!"><div id="card-stack"></div>

Save line breaks (in database)

The premise of this question is flawed, as the newlines are stored in the database already.

At least as long as you haven't done anything to remove them prior to saving the input, that is.

The question should be how to display the newlines in HTML pages, and for this you have a couple of methods.

  • Either use a <pre> tag around the output. This will cause the text to be showns preformatted, and thus include the newlines as actual content. The bad side about this is that the text won't break normally, and as such can (and will) break out of the natural flow of your page.
  • Or use nl2br() or a custom nl2p() function, when echoing the content to the browser. This translates the newlines into <br> (or <p>) tags, and will follow the normal flow of your site's layout. Which makes this the recommended method.

PS: This line is wrong:

 $description = nl2br($descriptionraw);

This is function to format output to a HTML-compatible viewer, a database is not. Using nl2br() and similar functions before you save stuff to the database will only cause you headaches, especially if you ever want to view the data in something that is not equipped to handle HTML code. (Such as the native MySQL client.)

Quick and dirty examples, using PDO:
First for saving the data:

$input = filter_var ($_POST['input'], FILTER);
$stmt = $db->prepare ("INSERT INTO `table`(`input`) VALUES (:data)");
$stmt->exec (array (':data' => $input));

Then for displaying it:

$output = '';
$res = $db->exec ("SELECT `input` FROM `table`");
foreach ($res->fetchArray () as $row) {
$output .= nl2br ($row['input']);
}
echo $output;

Preserve Line Breaks From TextArea

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");

    // will output
    This<br />
    is<br />
    a<br />
    string<br />
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Store the line break from textarea , store to database and show on frontend?

It does store linebreaks, but when you do output in HTML you can not see it.
Use nl2br() function to convert linebreaks into <br /> tag so you can see linebreaks in HTML.

If you want to prevent some HTML tags in the text - use strip_tags() function (you can allow some tags if you wish). And don't forget to use mysql_real_escape_string() or something like this to escape data.

How to keep linebreaks in html textarea POST data

Here is what finally solved the issue: I was using PHP's filter FILTER_FLAG_STRIP_LOW (http://php.net/manual/en/filter.filters.flags.php) on the string before you output or store to the database you will remove the newline characters \r\n .

To fix this issue you can use the FILTER_FLAG_ENCODE_LOW instead of FILTER_FLAG_STRIP_LOW as such:

$input = filter_var($input, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);

Save textarea to MySQL and preserve line breaks

mysql_real_escape_string doesn't remove line breaks, it escapes them.

It should work okay to escape the string when storing it, and applying nl2br (possibly in combination with htmlspecialchars() to prevent users from entering raw HTML) when the data is output. That's the best way to go.

Javascript textarea line break into database for result as JSON String

Json line which created this error

"My name is example 
My name is example"}

That is not valid JSON to begin with.

In JavaScript, a text literal delimited by single or double quotes, can not contain an actual line break. It would either need an \ at the end of every line, or the line breaks would need to be replaced with the characters \n inside the text literal.

It is important to always properly differentiate between data, and code.

When you read the field value using $(this).val(), the result is data. In there, you have an actual line break, hexadecimal byte value 0A.

But JSON is code, it needs to get parsed. So it has to follow the basic syntax rules for text literals, that JavaScript imposes.

So those line breaks would need to be replaced by the characters \n, which can be done simply by

someVariableContainingText = someVariableContainingText.replace(/\n/g, "\\n")

That would get you "My name is example\nMy name is example" here, and that now is a valid JS text literal. As soon as your JSON contains that, instead of an actual line break, it can be parsed properly.



Related Topics



Leave a reply



Submit