Home:ALL Converter>How to store and retrieve text data in MySQL preserving the line breaks?

How to store and retrieve text data in MySQL preserving the line breaks?

Ask Time:2012-12-06T15:15:18         Author:Jhon Andrew

Json Formatter

How can I store and retrieve data in MySQL database from a textarea but preserving the line-breaks? How can I also do it in a safest way where users can not do Cross-Site Scripting or SQL Injection attacks?

Should I filter first the user's input data through mysql_real_escape() function then INSERT INTO the database and then when retrieving, use htmlspecialchars() function?

I just want to know how to store data safely and preserving the line-breaks. I hope someone could do me an example like this:

<?php
    $con = mysql_connect(host,username,password);
    mysql_select_db(contents_db);

    //Filtering process to prevent SQL-Injection
    $content = mysql_real_escape($_POST['content']);

    mysql_query('INSERT INTO contents_db (content, time) VALUES ({$content},{time()}');

    if(mysql_insert_id() > 1){
        $query = mysql_query('SELECT * FROM contents_db ORDER BY time DESC LIMIT 1');
        $text = mysql_fetch_object($query);

        //Outputting process to preserve line-breaks
        echo htmlspecialchars($text->content);
    }

    mysql_close($con);
?>

If my example is right already, can anyone show me how to make it even better and safer?

Author:Jhon Andrew,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/13738690/how-to-store-and-retrieve-text-data-in-mysql-preserving-the-line-breaks
yy