Hello,

I have a made a forum like page where a user can submit a thread and the information gets stored in a database. However, when I try to output the data it outputs it without any line breaks in it, example:
The user inputs:
Hello,

This a paragraph

It would output like this:
Hello, This is a paragraph

I can confirm that in my database the line breaks are saved so I believe the problem is only in the displaying. This is my code used to output the information:

{Top of page}

<?php

    session_start();

    //Connected to database here

    $username = $_SESSION['username'];

    $query = "select * from threads3 where tableID='{$_GET['threadID']}'";

    $result = mysql_query($query, $conn) or die(mysql_error());

    $getinfo = mysql_fetch_row($result);

    $title = $getinfo[6];
    $content = $getinfo[8];
    $creator = $getinfo[2];

    mysql_close($conn);

?>

{output code}
        <div align='center' id='threadContentZ'>
            <p id='threadContent'><?php echo $content; ?></p>
        </div>

Recommended Answers

@Yorkiebar14

You need to put \n at the end.

preg_replace( "/\r|\n/", "", $yourString );

Jump to Post

Try this:

function nl2br2($string) 
{ 
    $string = str_replace(array("\r\n", "\r", "\n"), '<br />', $string); 
    return $string; 
}
Jump to Post

Try:

<p id='threadContent'><?php echo nl2br($content); ?></p>
Jump to Post

All 7 Replies

Re: Can't get linebreaks from database 80 80
Member Avatar

@Yorkiebar14

You need to put \n at the end.

preg_replace( "/\r|\n/", "", $yourString );

Re: Can't get linebreaks from database 80 80

I wasn't to sure what you wanted me to do but I tried using the line you gave (with the variable changed to mine obviously) but it gave me nothing at all.

Re: Can't get linebreaks from database 80 80
Member Avatar

Try this:

function nl2br2($string) 
{ 
    $string = str_replace(array("\r\n", "\r", "\n"), '<br />', $string); 
    return $string; 
}  
Re: Can't get linebreaks from database 80 80
Member Avatar

Try:

<p id='threadContent'><?php echo nl2br($content); ?></p>
commented: Nice ! +4
Re: Can't get linebreaks from database 80 80

Thanks guys, diafols code got it working :D

Re: Can't get linebreaks from database 80 80

Just to add some clarification here, there was never a problem with your database. It's simply that HTML does not preserve line breaks, so you need to use the nl2br() function to turn new line breaks into HTML line breaks.

Re: Can't get linebreaks from database 80 80

Yeh mate, I stated that I could see the line breaks in my database so I thought the problem was in the output. Thanks anyway for clarifying it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.