Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Form Not Picking Up Line Breaks

    I have created a form for storing user comments. All messages are displayed without line breaks.

    usercomments in the name of the field which stores user comments. I have tried :

    PHP Code:
    $_POST['usercomments'] = nl2br($_POST['usercomments']); 
    But it's not working.

    I'm not sure if this is relevant to the problem but just in case when I display results they're converted into arrays :

    PHP Code:
    $cmtusername $board['username'];
    $cmtsubject $board['subject'];
    $comments $board['usercomments'];
    $cmtdate $board['dateofcomment'];
    $timestamp strtotime($cmtdate); 
    $new_date date('F j, Y, g:ia'$timestamp); 

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    I'm assuming you are using textarea in your form?
    And the name of the textarea is 'usercomments'?

    Looking at this line:
    The part is red is wrong.
    $_POST['usercomments'] = nl2br($_POST['usercomments']);

    You need that to be a variable, like this:
    $usercomments = nl2br($_POST['usercomments']);

    Now, echo it to test ...

    echo $usercomments;

  • #3
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    I'm assuming you are using textarea in your form?
    And the name of the textarea is 'usercomments'?

    Looking at this line:
    The part is red is wrong.
    $_POST['usercomments'] = nl2br($_POST['usercomments']);

    You need that to be a variable, like this:
    $usercomments = nl2br($_POST['usercomments']);

    Now, echo it to test ...

    echo $usercomments;
    I've checked the table and it records the line breaks, including those I entered before using nl2br but when I process it they're not displayed. The textarea is named usercomments.

    PHP Code:
    <?php
    session_start
    ();
    include 
    "common.php";
    $message $_GET['message'];
    //COLLECT POST data
    $formValue=array();
    foreach (
    $_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    $comments nl2br($_POST['usercomments']);
    This is the textarea :

    Code:
    <div><label for="yourcomments">Your Comments</label><textarea id="usercomments" name="usercomments" class="comment"></textarea></div>
    And this is how I process everything and display it :

    PHP Code:
    <?php //fetch results and convert into an array

    WHILE($board mysql_fetch_array($result)):

    $cmtusername $board['username'];
    $cmtsubject $board['subject'];
    $comments $board['usercomments'];
    $cmtdate $board['dateofcomment'];
    $timestamp strtotime($cmtdate); 
    $new_date date('j F Y, g:i a'$timestamp);

    echo 
    '

    <br style="clear:left;"/>

    <div class="cmtform"><h2>Subject : '
    .$cmtsubject.'. Posted by '.$cmtusername.' on '.$new_date.'</h2><br />
    '
    .$comments.'</div>'
    ;

    endwhile;

    ?>
    Last edited by Mehdi72; 12-31-2013 at 03:53 AM.

  • #4
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    Oh, I see now ... it's when you get the text from your MySQL table, the linebreaks are lost. Is that correct?

    I have an idea ...

    Before you save it to your table, change all of the newlines to a character not normally used ... example: the pipe |

    Save the text with the pipes | replacing all newline characters. When you restore it back to the <textarea>, change the pipes to /n characters.

    So, you won't be using any <br /> unless you display the text outside of a <textarea>.

  • #5
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    Oh, I see now ... it's when you get the text from your MySQL table, the linebreaks are lost. Is that correct?
    Yes. I should have checked the database tables before posting.

    I have an idea ...

    Before you save it to your table, change all of the newlines to a character not normally used ... example: the pipe |

    Save the text with the pipes | replacing all newline characters. When you restore it back to the <textarea>, change the pipes to /n characters.

    So, you won't be using any <br /> unless you display the text outside of a <textarea>.
    Stored comments are displayed in a comments box outside of the textarea. I'm not sure how to change the newlines to a pipe. This is how the data is written into the table :

    PHP Code:
    $Query "INSERT INTO $Table_3 VALUES ('0', '".mysql_escape_string($formValue["username"])."','".mysql_escape_string($formValue["subject"])."',NOW(),'".mysql_escape_string($formValue["usercomments"])."')"
    The first value is the ID field (primary key).

  • #6
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    Totally untested ... but this would be the place to do the switch - before you save $comments in the database table.

    PHP Code:
    <?php
    session_start
    ();
    include 
    "common.php";
    $message $_GET['message'];
    //COLLECT POST data
    $formValue=array();
    foreach (
    $_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    $comments str_replace("\n","|",($_POST['usercomments'])); 

    // or this?
    // I'm not sure if your textarea newline is \n or \r\n ...

    $comments str_replace("\r\n","|",($_POST['usercomments'])); 

    ?>
    After doing that, use your Mysql Admin to browse the table and see if the pipes exist where the "newlines" used to be.

    There is also something not right with $comments. Your table insert uses: usercomments (which is $usercomments).
    By showing your snippets of script in small pieces, I can't figure out which part comes first, and when the variable name got changed.


    .
    Last edited by mlseim; 12-31-2013 at 10:57 PM.

  • #7
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    Totally untested ... but this would be the place to do the switch - before you save $comments in the database table.

    PHP Code:
    <?php
    session_start
    ();
    include 
    "common.php";
    $message $_GET['message'];
    //COLLECT POST data
    $formValue=array();
    foreach (
    $_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    $comments str_replace("\n","|",($_POST['usercomments'])); 

    // or this?
    // I'm not sure if your textarea newline is \n or \r\n ...

    $comments str_replace("\r\n","|",($_POST['usercomments'])); 

    ?>
    After doing that, use your Mysql Admin to browse the table and see if the pipes exist where the "newlines" used to be.

    There is also something not right with $comments. Your table insert uses: usercomments (which is $usercomments).
    By showing your snippets of script in small pieces, I can't figure out which part comes first, and when the variable name got changed.


    .
    Didn't work. I checked the table in mysql and it doesn't show the pipes, it picks up the line breaks but doesn't show the pipes.

    Here's the page with content removed :

    PHP Code:
    <?php
    session_start
    ();
    include 
    "common.php";
    $message $_GET['message'];
    $formValue=array();
    foreach (
    $_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    $comments str_replace("\n","|",($_POST['usercomments']));
    $_SESSION['post_vars'][$key] = $value;
    }
    //close for loop
    if(isset($_POST['Submit'])){
    //Check for empty fields 
    if($formValue['username']=="" || $formValue['subject']=="" || $formValue['usercomments']==""){

    $message "Please enter data in the form" ;
    header("Location: oldcommentsboard.php?message=$message");

    }else{    
    DBConnect();
    $Link mysql_connect($Host$User$Password);

    //Inserts the data entered in the form into the db table and records the date and time the comment is posted

    $Query "INSERT INTO $Table_3 VALUES ('0', '".mysql_escape_string($formValue["username"])."','".mysql_escape_string($formValue["subject"])."',NOW(),'".mysql_escape_string($formValue["usercomments"])."')";

    if(
    mysql_db_query ($DBName$Query$Link)){
    $message "Thank you for your comments";
    header("Location: oldcommentsboard.php?message=$message");
    }else{
    $message "Error Inserting!";
    header("Location: oldcommentsboard.php?message=$message");

    }
    }
    }

    ?>

    <?php
    //connect to the server
    $connect mysql_connect("localhost","username","password");

    //connect to the database
    mysql_select_db("mydatabase");

    //query the database
    $result mysql_query("SELECT * FROM comments");

    ?>

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">

    <?php echo $comments ?>

    <div class="container">
        
    <div id="navigation">
    <ul>
    </ul>

    <div class="formcontainer">

    <div class="phpmessage">
    <?php print $message ?>
    </div>

    <form action="oldcommentsboard.php?CreateRecord=1" method="post" enctype="multipart/form-data" name="form1" id="genericForm">

    <fieldset>
    <legend><span class="formheading">Post a Comment</span></legend>

    <div class="registerform">
    <div><label for="username">Name</label><input id="username" class="insetcomments" name="username" type="text" /></div>
    <div><label for="subject">Subject</label><input id="subject" class="insetcomments" name="subject" type="text" /></div>

    <div><label for="yourcomments">Your Comments</label><textarea id="usercomments" name="usercomments" class="comment"></textarea></div>

    <div class="submit"><input name="Reset" type="reset" class="resetcbtn" value="Reset"/></div>
    <div class="submit"><input name="Edit" type="submit" class="editcbtn" value="Edit"/></div>
    <div class="submit"><input name="Submit" type="submit" class="submitcbtn" value="Post"></div>

    </div>
    </fieldset>
    </form>


    <br style="clear:left;"/>

    <?php //fetch results and convert into an array

    WHILE($board mysql_fetch_array($result)):

    $cmtusername $board['username'];
    $cmtsubject $board['subject'];
    $comments $board['usercomments'];
    $cmtdate $board['dateofcomment'];
    $timestamp strtotime($cmtdate); 
    $new_date date('j F Y, g:i a'$timestamp);

    echo 
    '

    <br style="clear:left;"/>

    <div class="cmtform">
    <h2>Subject : '
    .$cmtsubject.'. Posted by '.$cmtusername.' on '.$new_date.'</h2><br />
    '
    .$comments.'
    </div>'
    ;

    endwhile;

    ?>

    </body>
    </html>
    I checked my sendmail.php to see how I processed an email form for a different website (it picks up line breaks) :

    PHP Code:
    "Comments : \n\n".clean_string($Comments)."\n"
    I tried to used clean_string instead of str_replace but I'm getting syntax errors.
    Last edited by Mehdi72; 01-01-2014 at 01:03 AM.

  • #8
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    Before you try other things ....

    change this:
    $comments = str_replace("\n","|",($_POST['usercomments']));

    to this:
    $comments = str_replace("\r\n","|",($_POST['usercomments']));

    and see if the pipes appear in the table.

  • #9
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    Before you try other things ....

    change this:
    $comments = str_replace("\n","|",($_POST['usercomments']));

    to this:
    $comments = str_replace("\r\n","|",($_POST['usercomments']));

    and see if the pipes appear in the table.
    Nope. I get line breaks but no pipes in the table itself and on the page the comments are still displayed without line breaks.

  • #10
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    One more attempt ...

    I see something that I was questioning before but didn't know where it was ... I see it ...

    You are putting $formvalue["usercomments"] into your table.
    That has not been affected in any way.

    Right before you do the insert, you need to replace the newlines ...
    And that variable is what gets inserted into your table.

    $comments = str_replace("\n","|",($formValue["usercomments"]));
    $Query = "INSERT INTO $Table_3 VALUES ('0', '".mysql_escape_string($formValue["username"])."','".mysql_escape_string($formValue["subject"])."',NOW(),'".mysql_escape_string($comments)."')";

    Again, if that doesn't work, try "\r\n" instead. Not sure if your newline is "\n" or "\r\n"

  • Users who have thanked mlseim for this post:

    Mehdi72 (01-02-2014)

  • #11
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mlseim View Post
    One more attempt ...

    I see something that I was questioning before but didn't know where it was ... I see it ...

    You are putting $formvalue["usercomments"] into your table.
    That has not been affected in any way.

    Right before you do the insert, you need to replace the newlines ...
    And that variable is what gets inserted into your table.

    $comments = str_replace("\n","|",($formValue["usercomments"]));
    $Query = "INSERT INTO $Table_3 VALUES ('0', '".mysql_escape_string($formValue["username"])."','".mysql_escape_string($formValue["subject"])."',NOW(),'".mysql_escape_string($comments)."')";

    Again, if that doesn't work, try "\r\n" instead. Not sure if your newline is "\n" or "\r\n"
    What happens now is the value in quotes here :

    PHP Code:
    [COLOR="Red"]$comments[/COLOR] = str_replace("\n","|",($formValue["usercomments"])); 
    Is displyed in the comments. The above shows the pipes in the comments, this :

    PHP Code:
    $comments str_replace("\n","r",($formValue["usercomments"])); 
    With the following entered in the textarea :

    7.05pm this is the first line
    7.05pm this is the second line

    7.05pm this is the fourth line after two carriage returns
    Is displayed as :

    7.05pm this is the first line r7.05pm this is the second line r r7.05pm this is the fourth line after two carriage returns
    And in the table :

    7.05pm this is the first line
    r7.05pm this is the second line
    r
    r7.05pm this is the fourth line after two carriage returns
    So it records the carriage return as 'r'.

    I don't think that method is going to work!

  • #12
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    1
    Thanked 6 Times in 6 Posts
    Going back to the first post:

    Quote Originally Posted by Mehdi72 View Post
    I have tried :

    PHP Code:
    $_POST['usercomments'] = nl2br($_POST['usercomments']); 
    But it's not working.

    The nl2br function worked all along but you did not store its return value in the database (as mentioned in post #10).

    Do not try to replace newlines with pipes! Stick with nl2br.

    ---

    I have a few questions about the code in post #7

    1. Why do you use the old mysql functions? Do you know about the newer and generally recommended PHP Data Objects?

    2. Did you really mean to call the strip_tags function on every value in the $_POST array or did you not know about the htmlspecialchars function?

    3. Line 3
    Code:
    $comments = str_replace("\n","|",($_POST['usercomments']));
    does not belong inside the loop.

    4. Can you explain why you use redirects in line 16, 28 and 31?

    5. You should check your HTML code because you are missing some tags. Most noticeably </head> and <body>.
    Last edited by hBGl; 01-02-2014 at 01:36 AM.

  • Users who have thanked hBGl for this post:

    Mehdi72 (01-02-2014)

  • #13
    Regular Coder
    Join Date
    Jul 2007
    Location
    England
    Posts
    132
    Thanks
    24
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by hBGl View Post
    Going back to the first post:

    The nl2br function worked all along but you did not store its return value in the database (as mentioned in post #10).
    Oh crap, I must have forgot to change all references to the string e.g. here :

    $comments = $board['usercomments'];

    To : $usercomments = $board['usercomments'];

    PHP Code:
    $usercomments nl2br($_POST['usercomments']); 
    Do not try to replace newlines with pipes! Stick with nl2br.
    Ok. It's working now!

    I have a few questions about the code in post #7

    1. Why do you use the old mysql functions? Do you know about the newer and generally recommended PHP Data Objects?
    I was told about it earlier in the week but I learned a bit of php a few years ago and want to work with my existing code as I understand it better before moving on. It's not for commercial use so it's not necessary at this stage for me to be up to date. Once I get a better understanding of the basics I can look into mysqli. What I find confusing is there several ways to perform the same functions.

    2. Did you really mean to call the strip_tags function on every value in the $_POST array or did you not know about the htmlspecialchars function?
    I don't understand what it does.

    3. Line 3
    Code:
    $comments = str_replace("\n","|",($_POST['usercomments']));
    does not belong inside the loop.
    Ok.

    4. Can you explain why you use redirects in line 16, 28 and 31?
    It's not a redirect. The page is called oldcommentsboard.php so the message variable is displayed on the same page e.g. when the user does not fill in one the input boxes an error message is displayed on the same page.

    5. You should check your HTML code because you are missing some tags. Most noticeable </head> and <body>.
    I left out most of the HTML content in my post because it's not relevant to the php issues. Unlike php, HTML5 & CSS3 I understand, the page validates without any errors - excluding the Using experimental feature validator throws up.
    Last edited by Mehdi72; 01-02-2014 at 01:42 AM.

  • #14
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,502
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    nl2br is fine to use, but if you strip HTML tags, those will be gone ... that's why I mentioned using pipes | or some other normally not-used character.

    You're right, there are a few ways to do the same thing. Only professional programmers (like Fou-Lu) will know what the best solution is.

  • #15
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    1
    Thanked 6 Times in 6 Posts
    Quote Originally Posted by Mehdi72 View Post
    Oh crap, I must have forgot to change all references to the string e.g. here :

    $comments = $board['usercomments'];

    To : $usercomments = $board['usercomments'];

    PHP Code:
    $usercomments nl2br($_POST['usercomments']); 


    Ok. It's working now!
    That's great.

    Quote Originally Posted by Mehdi72 View Post
    I was told about it earlier in the week but I learned a bit of php a few years ago and want to work with my existing code as I understand it better before moving on. It's not for commercial use so it's not necessary at this stage for me to be up to date. Once I get a better understanding of the basics I can look into mysqli. What I find confusing is there several ways to perform the same functions.
    Nothing wrong with that.

    Quote Originally Posted by Mehdi72 View Post
    I don't understand what it does.
    The htmlspecialchars function escapes characters that have special meaning in HTML. That way you can make sure that the comment does not screw up your webpage and that it still gets displayed correctly.

    This example shows the difference between htmlspecialchars and strip_tags:

    PHP Code:
    $comment 'Hi there. I wrote some HTML today check it out: <p>Hello</p>';

    echo 
    strip_tags($comment);
    echo 
    '<br />';
    echo 
    htmlspecialchars($comment); 
    That code outputs the following:
    Hi there. I wrote some HTML today check it out: Hello<br />Hi there. I wrote some HTML today check it out: &lt;p&gt;Hello&lt;/p&gt;

    strip_tags removed the <p> and </p> tags whereas htmlspecialchars just replaced the < and > characters with their respective HTML entities &lt; and &gt;. If you don't know about HTML entities take a look at this: http://www.w3schools.com/html/html_entities.asp

    Quote Originally Posted by Mehdi72 View Post
    It's not a redirect. The page is called oldcommentsboard.php so the message variable is displayed on the same page e.g. when the user does not fill in one the input boxes an error message is displayed on the same page.
    It is still a redirect even if you redirect to the same script. You can read more about it in the PHP documentation:

    The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.
    PHP Code:
    <?php
    header
    ("Location: http://www.example.com/"); /* Redirect browser */

    /* Make sure that code below does not get executed when we redirect. */
    exit;
    ?>
    Source: http://www.php.net/manual/en/function.header.php

    In your code the call to header("Location: ... effectively does nothing. You have already set the $message variable (line 15, 27, 30) then you redirect and set the $message variable (line 4) again.

    Another thing is that the call to header("Location: ... does not terminate the current script. The rest of the script is executed.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •