php mysql storing line breaks in text area in database

49,162

Solution 1

The line breaks in the text area are linebreak characters such as \n. These are not rendered in HTML and thus they won't show up if you simply echo the output. You can echo inside of a <textarea> or a <pre> tag or you can use the nl2br() to replace new lines with <br> tags so that it can be displayed as HTML.

Solution 2

You can escape the line breaks before storing by using mysql_real_escape_string

Documentation here: http://php.net/manual/en/function.mysql-real-escape-string.php

Solution 3

you can also use javascript to break the text as \n to <br> by using replace

str.replace("\n", "<br />","g");
Share:
49,162
neeko
Author by

neeko

Updated on July 29, 2022

Comments

  • neeko
    neeko almost 2 years

    I have an input textarea and I would like to store the line breaks that a user makes in the text area in the database, so that it echoes the output text the same way as in the input text

    eg:

    Some text some text some text some text
    
    
    new line some text some text new line 
    
    new line some text new line some text
    

    this is my current upload script:

    $sql = "insert into people (price, contact, category, username, fname, lname, expire, filename) values (:price, :contact, :category, :user_id, :fname, :lname, now() + INTERVAL 1 MONTH, :imagename)";
    $q = $conn->prepare($sql) or die("failed!");
    $q->bindParam(':price', $price, PDO::PARAM_STR);
    $q->bindParam(':contact', $contact, PDO::PARAM_STR);
    $q->bindParam(':category', $category, PDO::PARAM_STR);
    $q->bindParam(':user_id', $user_id, PDO::PARAM_STR);
    $q->bindParam(':fname', $fname, PDO::PARAM_STR);
    $q->bindParam(':lname', $lname, PDO::PARAM_STR);
    $q->bindParam(':imagename', $imagename, PDO::PARAM_STR);
    $q->execute();