【问题标题】:How to store and retrieve text data in MySQL preserving the line breaks?如何在 MySQL 中存储和检索文本数据,保留换行符?
【发布时间】:2012-11-24 04:35:27
【问题描述】:

如何从textarea 存储和检索 MySQL 数据库中的数据但保留换行符?在用户无法进行跨站脚本或 SQL 注入攻击的情况下,如何以最安全的方式进行操作?

我是否应该先通过mysql_real_escape()函数过滤用户输入数据,然后INSERT INTO数据库,然后在检索时使用htmlspecialchars()函数?

我只想知道如何安全地存储数据并保留换行符。我希望有人能给我一个这样的例子:

<?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);
?>

如果我的例子已经正确,谁能告诉我如何让它变得更好、更安全?

【问题讨论】:

  • 对于初学者,{$content} 周围没有引号
  • 与其想知道你的例子是否正确,不如继续测试它。
  • 离题:不要使用 mysql_* 函数 - 它们已弃用。更好地使用 PDO(或 mysqli_*)和准备好的语句。
  • echo nl2br($text-&gt;content);
  • 旁注:这样做SELECT 并基于time DESC 进行排序如果在选择一个之前插入两行(考虑并发请求),则不会给您预期的结果。

标签: php mysql filter


【解决方案1】:

这是使用 PDO 的完整示例。举个例子,您可以通过多种方式对其进行改进(例如,创建像 getDatabaseResult($query) 这样的单个函数以使查询异常检查更容易)。

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']);
}

【讨论】:

    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多