如何从MySQL数据库中存储和检索textarea中的数据,但又能保留换行符?在用户无法执行跨站点脚本或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);
?>如果我的例子已经正确,有人能告诉我如何使它变得更好和更安全吗?
发布于 2012-12-06 07:35:03
这是使用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']);
}https://stackoverflow.com/questions/13738690
复制相似问题