On my website, users have the ability to post comments. Comments get inserted into my mysql database as plain text. When displaying the comments back, I am trying to use the php nl2br() function to allow it to display line breaks as <br /> tags, but it doesn't work. I've noticed when the text gets posted to the database it does not capture the '\n'. Should it? I'd really appreciate if anyone could help with why carriage returns are not being captured / displayed right.

The following code gets the comment and formats it safe before inserting to the database.

$comment = $_GET["comment"];
	$comment = stripslashes($_GET["comment"]);
	$comment = $_GET["comment"];
$comment = trim($comment);
$comment = preg_replace('/\s+/', ' ', $comment);
$comment = mysql_real_escape_string($comment);
$comment = ereg_replace("<[^>]*>","",$comment);

I am then trying to display it as:

echo nl2br(htmlentities($row["comment"]));

**Note: I've tried commenting out everything but the "$comment = $_GET["comment"];" line before inserting to database, but still no luck. I've also tried removing the htmlentities before displaying, but no luck.


7 Years
Discussion Span
Last Post by keepbusy

I would use post for something like this. I am not sure how the url handles newlines.

Also, mysql_real_escape_string messes up line breaks. You need to run nl2br before inserting into the database.


I agree with all of you that GET may be the big problem here. Good call. The reason I am doing a GET is because I'm using AJAX and I wasn't sure the correct syntax for doing a POST. If anyone knows off hand, much appreciated, otherwise I'll keep researching.


This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.