简体   繁体   中英

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

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?

Thats full example of using PDO . Just example, you can improve it in many ways (for example, create single function like getDatabaseResult($query) to make queries exceptions check easier).

try{
    $PDO = new PDO("mysql:host=".$db_host.";dbname=".$db_name, $db_user, $db_pass);
}
catch(PDOException $e){
    die('mysql connection error');
}

// if post data is set - add new row
if(isset($_POST['content']))
{
    try{
        $query = $PDO->prepare('INSERT INTO contents_db (content, time) VALUES ?,?');
        $res   = $query->execute(array($content,time()));
    }
    catch(PDOException $e){
        die('insert query failed');
    }
}

// if last query was executed - select data
// or you can call for "$PDO->lastInsertId();"
if($res){
    try{
        $query = $PDO->prepare('SELECT * FROM contents_db ORDER BY time DESC LIMIT 1');
        $res   = $query->execute();
        $res   = $query->fetchAll(PDO::FETCH_ASSOC);
    }
    catch(PDOException $e){
        die('select query failed');
    }

    //Outputting process to preserve line-breaks
    echo nl2br($text['content']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM