如何逃避输入,但保存未转义到数据库

编程入门 行业动态 更新时间:2024-10-21 23:10:51
本文介绍了如何逃避输入,但保存未转义到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据说,为了防止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');

更多推荐

如何逃避输入,但保存未转义到数据库

本文发布于:2023-10-25 08:23:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!