mysql_real_escape_string pdo,函数mysql_real_escape_string的PDO等效项是什么?

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?

解决方案

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()

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.

# Example:

Below is an example of a safe database query using prepared statements (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.

It is worth noting that you should pass a charset=utf8 as attribute, in your DSN as seen above, for security reasons, and always enable

PDO to show errors in the form of exceptions.

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

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

Good reads

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值