php 什么是函数 mysql_real_escape_string 的 PDO 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14012642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:26:30  来源:igfitidea点击:

What is the PDO equivalent of function mysql_real_escape_string?

phpmysqlpdosql-injection

提问by REJOLA

I am modifying my code from using mysql_*to PDO. In my code I had mysql_real_escape_string(). What is the equivalent of this in PDO?

我正在修改我的代码,从 usingmysql_*PDO. 在我的代码中,我有mysql_real_escape_string(). 这在 PDO 中的等价物是什么?

回答by samayo

Well No, there is none!

不,没有!

Technically there is PDO::quote()but it is rarely ever used and is not the equivalent of mysql_real_escape_string()

从技术上讲有,PDO::quote()但很少使用,也不等同于mysql_real_escape_string()

That's right!If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.

这是正确的!如果您已经按照使用准备好的语句记录的正确方式使用 PDO ,那么它将保护您免受 MySQL 注入。



# Example:

# Example:

Below is an example of a safedatabase query using prepared statements (pdo)

以下是使用准备好的语句 (pdo)的安全数据库查询 示例

  try {
     // first connect to database with the PDO object. 
     $db = new \PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [
       PDO::ATTR_EMULATE_PREPARES => false, 
       PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
     ]); 
 } catch(\PDOException $e){
     // if connection fails, show PDO error. 
   echo "Error connecting to mysql: " . $e->getMessage();
 }

And, now assuming the connection is established, you can execute your query like this.

而且,现在假设连接已建立,您可以像这样执行查询。

if($_POST && isset($_POST['color'])){ 

    // preparing a statement
    $stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");

    // execute/run the statement. 
    $stmt->execute(array($_POST['color']));

    // fetch the result. 
    $cars = $stmt->fetchAll(\PDO::FETCH_ASSOC); 
    var_dump($cars); 
 }

Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.

现在,正如您可能会说的,我没有使用任何东西来转义/清理$_POST["color"]. 由于 PDO 和准备好的语句的强大功能,这段代码是安全的,不会被 myql 注入。



It is worth noting that you should pass a charset=utf8as attribute, in your DSNas seen above, for security reasons, and always enable PDO to show errors in the form of exceptions.

值得注意的是,出于安全原因,您应该charset=utf8DSN如上所示传递as 属性,并始终启用 PDO 以异常形式显示错误。

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.

因此,您的数据库查询中的错误不会泄露您的目录结构、数据库用户名等敏感数据。

Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ]as described in this answer

最后但并非最不重要的一点是,有些时候您不应该 100% 信任 PDO,并且必然会采取一些额外措施来防止 sql 注入,其中一种情况是,如果您使用过时的 mysql 版本,[ mysql =< 5.3.6 ]如本文所述回答

But, using prepared statements as shown above will always be safer, than using any of the functions that start with mysql_

但是,使用如上所示的准备好的语句总是比使用任何以 mysql_

Good reads

好读

PDO Tutorial for MySQL Developers

MySQL 开发人员的 PDO 教程

回答by Ry-

There is none*! The object of PDO is that you don't have to escape anything; you just send it as data. For example:

空无一人*!PDO 的目标是你不必逃避任何事情;您只需将其作为数据发送即可。例如:

$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;');
$query->execute([':name' => $username]); # No need to escape it!

As opposed to:

与之相反:

$safe_username = mysql_real_escape_string($username);
mysql_query("SELECT * FROM users WHERE username = '$safe_username' LIMIT 1;");

* Well, there is one, as Michael Berkowski said! But there are better ways.

* 嗯,有一个,正如 Michael Berkowski 所说!但是有更好的方法。

回答by Simo

$v = '"'.mysql_real_escape_string($v).'"'; 

is the equivalent of $v = $this->db->quote($v);be sure you have a PDO instance in $this->dbso you can call the pdo method quote()

相当于$v = $this->db->quote($v);确保您有一个 PDO 实例,$this->db以便您可以调用 pdo 方法quote()

回答by IMRA

There is no need of mysql_real_escape_stringin PDO.

PDO 中不需要mysql_real_escape_string

PDO itself adjust special character in mysql query ,you only need to pass anonymous parameter and bind it run time.like this Suppose you have user table with attribute name,email and password and you have to insert into this use prepare statement like this you can pass name as => $name="Rajes'h ";

PDO本身在mysql查询中调整特殊字符,你只需要传递匿名参数并在运行时绑定它。像这样假设你有一个带有属性名称,电子邮件和密码的用户表,你必须像这样插入到这个use prepare语句中,你可以传递名称为 => $name="Rajes'h ";

it should execute there is no need of equivalent of mysql_real_escape_string

它应该执行,不需要相当于mysql_real_escape_string

$stmt="INSERT into user(name,email,password) VALUES(:name,:email,:password)";
try{
   $pstmt=$dbh->prepare($stmt);//$dbh database handler for executing mysql query
   $pstmt->bindParam(':name',$name,PDO::PARAM_STR);
   $pstmt->bindParam(':email',$email,PDO::PARAM_STR);
   $pstmt->bindParam(':password',$password,PDO::PARAM_STR);
   $status=$pstmt->execute();
   if($status){
    //next line of code 
   }


}catch(PDOException $pdo){
     echo $pdo->getMessage();
}

回答by Andrew Foster

In response to a lot of people's comments on here, but I can't comment directly yet (not reached 50 points), there ARE ACTUALLY needs to use the $dbh->quote($value)EVEN when using PDO and they are perfectly justifiable reasons...

在这里回应很多人的评论,但我还不能直接评论(未达到50分),实际上$dbh->quote($value)在使用PDO时需要使用EVEN,并且它们是完全合理的理由......

  1. If you are looping through many records building a "BULK INSERT" command, (I usually restart on 1000 records) due to exploiting InnoDb tables in MySQL/Maria Db. Creating individual insert commands using prepared statements is neat, but highly inefficient when doing bulk tasks!
  2. PDO can't yet deal with dynamic IN(...) structures, so when you are building a list of IN strings from a list of user variables, YOU WILL NEED TO $dbh->quote($value)each value in the list!
  1. 如果您在构建“BULK INSERT”命令的许多记录中循环,(我通常会在 1000 条记录上重新启动),因为利用 MySQL/Maria Db 中的 InnoDb 表。使用准备好的语句创建单个插入命令很简洁,但在执行批量任务时效率非常低!
  2. PDO 还不能处理动态 IN(...) 结构,因此当您从用户变量列表构建 IN 字符串列表时,您将需要$dbh->quote($value)列表中的每个值!

So yes, there is a need for $dbh->quote($value)when using PDO and is probably WHY the command is available in the first place.

所以是的,$dbh->quote($value)在使用 PDO 时需要,这可能是该命令首先可用的原因。

PS, you still don't need to put quotes around the command, the $dbh->quote($value)command also does that for you.

PS,您仍然不需要在命令周围加上引号,该$dbh->quote($value)命令也会为您做到这一点。

Out.

出去。

回答by IT goldman

If to answer the original question, then this is the PDO equivalent for mysql_real_escape_string:

如果要回答原始问题,那么这是 PDO 等效项mysql_real_escape_string

function my_real_escape_string($value, $connection) {
    /* 
    // this fails on: value="hello'";
    return trim ($connection->quote($value), "'");
    */
    return substr($connection->quote($value), 1, -1);       
}

btw, the mysqli equivalent is:

顺便说一句,mysqli 等价物是:

function my_real_escape_string($value, $connection) {
    return mysqli_real_escape_string($connection, $value);
}