Page 1 of 1

nl2br not working for mySQL result

Posted: Thu Oct 13, 2005 4:38 pm
by greatFade
I'm trying to get the content of an article from a mySQL (that part works,) however when I try to use nl2br with the string returned from mysql_result it doesn't work.

Here is the code by the way:

Code: Select all

<?php
	$sql = 'SELECT `article_content` '
        	. ' FROM `articles` '
        	. ' WHERE 1 AND `article_id` ='
		. $id . ' LIMIT 0, 30';

	$result = mysql_query($sql,$db);

	$content = mysql_result($result,0,"article_content");

	echo nl2br($content);

	mysql_close($db);
?>
It does print the content of the article, but instead of creating a newline, it just prints \n as it is stored in the database. Any suggestions?

Burrito: Please use

Code: Select all

tags when [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting PHP Code In The Forums[/url][/size]

Posted: Thu Oct 13, 2005 6:20 pm
by Sequalit
Try using the nl2br() function before you insert the article into the database, that way whenever you call it frmo the database its already there and formatted in html for ya.

here is an outline..

Code: Select all

$article = $_POST['articlefromtextarea'];
$article = nl2br($article);

mysql_query("insert into table values('$article');

$result = mysql_query("select from table $article where name='$artname'");
$text = mysql_result($result,0,article);

echo $text;

mysql_close().

Posted: Thu Oct 13, 2005 6:47 pm
by Jenk
Not the best solution ever, but it should work.

Code: Select all

<?php
    $sql = 'SELECT `article_content` '
            . ' FROM `articles` '
            . ' WHERE 1 AND `article_id` ='
        . $id . ' LIMIT 0, 30';

    $result = mysql_query($sql,$db);

    $content = str_replace('\n', "\n", mysql_result($result,0,"article_content"));

    echo nl2br($content);

    mysql_close($db);
?>
A better solution would to be to find out why your database contains the literal value of \n instead of the intended value (a line break).

Sounds like you are double escaping.

You should also be using htmlentities() to ensure nothing in the article will break from the html on your site.