Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line break from MySQL longtext to HTML via PHP

I have multiple lines of text entered into a single MySQL longtext cell that I would like to display in HTML. However, I cannot figure out how to keep the line break when the string is displayed in HTML.

For example, let's say I have this text in the column "content":

+-----------+
|  content  |
+-----------+
| Line 1.   |
|           |
| Line 2.   |
+-----------+

I want this to display:

Line 1.

Line 2.

However, I am getting this result with my PHP loop:

Line1.Line2.

I used the loop below to echo the text from my database. (I know I don't need a loop, but in the actual project I am displaying multiple rows of data).

$query = mysql_query("SELECT * FROM table ORDER BY timestamp DESC");
while($row = mysql_fetch_array($query)) {
    echo $row['title'];
}

In sum: How can I maintain line breaks when displaying a MySQL string in HTML? Is there any way to add <br> at the line breaks?

like image 842
JSW189 Avatar asked Dec 06 '22 14:12

JSW189


1 Answers

Try using php function nl2br (docs)

$content = "Line 1.\nLine 2.";
echo nl2br($content);
// output Line 1.<br>\nLine 2.
like image 70
Broncha Avatar answered Dec 09 '22 03:12

Broncha