Jay Kapoor
Jay Kapoor

Reputation: 21

php- new lines don't work when displaying data from mysql

I have a form where users can enter anything, for instance, suppose a user entered:

Hello World!
This is a new line.

This was written after two new lines.

The data that user submits using the form is inserted in DB:

$data = mysqli_real_escape_string($dbc, $_POST['text']);
$sql = "INSERT INTO data (Data) VALUES ('$data')";
$exec = mysqli_query($dbc, $sql);

Now it gets stored in database but when I fetch the text from the DB to show to the user, it displays:

Hello World! This is a new line. This was written after two new lines.

As you can see, the new lines are ignored. I also want to show line breaks.

I tried:

$data = mysqli_real_escape_string($dbc, str_replace('\n', '<br>', $_POST['text']));

but that doesn't work either. How can I show line breaks when displaying data from mysql?

Upvotes: 1

Views: 106

Answers (2)

Jerbot
Jerbot

Reputation: 1168

It is best to put your user input into the database unaltered (except for escaping, of course) in case you wish to query against the user input, or change your display behavior later on. That said, upon building your page and displaying the data, use

echo nl2br(htmlspecialchars($row['text'], ENT_QUOTES));

nl2br() converts all the "\r\n" or "\n" to <br /> so that it displays nicely. htmlspecialchars() converts any special characters the user typed into the field originally to proper html escape sequences.

Your code would work, except your \n should be wrapped in double quotes instead of single quotes. Single-quoted strings ignore escape sequences in PHP. However, as shown, a built-in function already exists for accomplishing this.

Upvotes: 2

chris85
chris85

Reputation: 23892

I believe you want nl2br. http://php.net/manual/en/function.nl2br.php The str_replace won't work because you'd need the \n in double quotes. As is you are searching for a literal '\n'.

$data = mysqli_real_escape_string($dbc, nl2br($_POST['text']));

Upvotes: 0

Related Questions