如何逃避输入,但保存未转义到数据库 [英] how to escape input but save unescaped into the database

查看:139
本文介绍了如何逃避输入,但保存未转义到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说,为了防止SQL注入,应该过滤输入数据,例如。使用addslashes或mysql_real_escape_string取决于使用的连接模块

It is said that in order to prevent from SQL injection one should filter the input data eg. with addslashes or mysql_real_escape_string depending on used connection modules

但是,使用addslashes转义的数据将以斜杠保存到数据库中,因此用户姓名将另存为O\ Reilly,而不是O'Reilly。需要使用striplashes来正确显示它。

However, data escaped with addslashes is being saved into the database WITH the slashes, so a user surname would save as O\'Reilly instead O'Reilly. The one needs to use stripslashes to display it correctly.

那么如何使用addslash并将其保存到数据库中而不使用斜杠?实际上是应该做的吗?

So how do I use addslashes and save into the database without slashes? Is it actually the way it should be done?

推荐答案

你不要使用 addslashes 您使用适当的DB特定转义功能,如 mysql_real_escape_string

You DONT use addslashes you use the appropriate DB specific escaping function like mysql_real_escape_string.

如果您使用PDO然后使用准备语句将转义变量作为绑定过程的一部分。在这种情况下,您需要做的就是:

if you are using PDO then using a prepared statement will escape the variables as part of binding process. In this case all you need to do is something like:

$pdo = new PDO($dsn, $user, $name);
$stmt = $pdo->prepare('INSERT INTO your_table (col1, col2,col3) VALUES (?, ?, ?)');
$stmt->execute(array('value 1', 'value 2', 'value 3');

或者为了额外的可读性和esier重用,您可以使用命名参数:

OR for extra readability and esier reuse you can use named params:

$pdo = new PDO($dsn, $user, $name);
$stmt = $pdo->prepare('INSERT INTO your_table (col1, col2,col3) VALUES (:col1, :col2, :col3)');
$stmt->execute(array(':col1' =>'value 1', ':col2' =>'value 2', ':col3' =>'value 3');

这篇关于如何逃避输入,但保存未转义到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆