gpt4 book ai didi

php - 如何在 MySQL 中存储和检索保留换行符的文本数据?

转载 作者:行者123 更新时间:2023-11-29 05:32:16 25 4
gpt4 key购买 nike

如何从 textarea 存储和检索 MySQL 数据库中的数据但保留换行符?在用户无法进行跨站点脚本或 SQL 注入(inject)攻击的情况下,我怎样才能以最安全的方式做到这一点?

我是否应该首先通过 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);
?>

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

最佳答案

这是使用 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']);
}

关于php - 如何在 MySQL 中存储和检索保留换行符的文本数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13738690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com