如何在pdo中逃脱字符串?(复制)

时间:2021-12-22 22:27:28

This question already has an answer here:

这个问题已经有了答案:

I would like to know how to escape strings in pdo . I have been escaping the springs like in the code bellow but now with pdo I do not know how to do it

我想知道如何在pdo中转义字符串。我一直在像下面的代码一样逃离弹簧,但是现在我不知道怎么做

$username=(isset($_POST['username']))? trim($_POST['username']): '';
$previlage =(isset($_GET['previlage']));
$query ="SELECT * FROM site_user 
WHERE username = '".mysql_real_escape_string($_SESSION['username'])."' AND  previlage ='Admin'";
$security = mysql_query($query)or die (mysql_error($con));
$count = mysql_num_rows($security);

2 个解决方案

#1


22  

Well, you can use PDO::quote, but, as said in its own docpage...

嗯,你可以使用PDO::quote,但是,正如它自己的docpage所说…

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement.

如果您正在使用这个函数来构建SQL语句,强烈建议使用PDO::prepare()来准备带有绑定参数的SQL语句,而不是使用PDO::quote()来插入用户输入到SQL语句中。

In your case it can look like this:

在你的例子中,它可以是这样的:

$query = "SELECT * 
            FROM site_user 
           WHERE username = :username AND previlage = 'Admin'";
$sth   = $dbh->prepare($query);
$sth->execute(array(':username' => $_SESSION['username']) );

#2


3  

mysql_* function will not work in PDO. WHY? Because PDO doesnt use mysql to connect to a databases, as far as input sanitization, PDO uses prepared statements you can find a good tutorial for that here: pdo

mysql_*函数在PDO中不能工作。为什么?因为PDO不使用mysql连接数据库,至于输入卫生处理,PDO使用准备好的语句,您可以在这里找到一个好的教程:PDO。

#1


22  

Well, you can use PDO::quote, but, as said in its own docpage...

嗯,你可以使用PDO::quote,但是,正如它自己的docpage所说…

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement.

如果您正在使用这个函数来构建SQL语句,强烈建议使用PDO::prepare()来准备带有绑定参数的SQL语句,而不是使用PDO::quote()来插入用户输入到SQL语句中。

In your case it can look like this:

在你的例子中,它可以是这样的:

$query = "SELECT * 
            FROM site_user 
           WHERE username = :username AND previlage = 'Admin'";
$sth   = $dbh->prepare($query);
$sth->execute(array(':username' => $_SESSION['username']) );

#2


3  

mysql_* function will not work in PDO. WHY? Because PDO doesnt use mysql to connect to a databases, as far as input sanitization, PDO uses prepared statements you can find a good tutorial for that here: pdo

mysql_*函数在PDO中不能工作。为什么?因为PDO不使用mysql连接数据库,至于输入卫生处理,PDO使用准备好的语句,您可以在这里找到一个好的教程:PDO。