nl2br not working for mySQL result

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
greatFade
Forum Newbie
Posts: 2
Joined: Tue Oct 11, 2005 12:36 pm

nl2br not working for mySQL result

Post 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]
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Post 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().
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
Post Reply