Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve Line Breaks From TextArea When Writing To MySQL

Tags:

html

php

mysql

I'm using a textarea to enable users to input comments. However, if the users enters new lines, the new lines don't appear when they are outputted. Is there any way to make the line breaks stay.

Any idea how do preserve the line breaks?

like image 929
Hirvesh Avatar asked Feb 19 '11 04:02

Hirvesh


People also ask

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

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.

How do you store line breaks in database?

Just put the output text between <pre></pre> tags, that will preserve the line breaks.

How do I add a line break in mysql?

-- Using both \r\n SELECT 'First line. \r\nSecond Line. ' AS 'New Line'; -- Using both \n SELECT 'First line.

How do you insert a line break in textarea?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.


2 Answers

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

like image 169
superUntitled Avatar answered Sep 19 '22 04:09

superUntitled


Here is what I use

$textToOutput = nl2br(htmlentities($text, ENT_QUOTES, 'UTF-8')); 

$text is the text that needs to be displayed $textToOutput is the returned text from nl2br and htmlentities so it can be safety displayed in the html context.
ENT_QUOTES will convert both double and single quotes, so you'll have no trouble with those.

like image 37
hiroki Avatar answered Sep 20 '22 04:09

hiroki