如何在 Yii 框架中使用 mysql_escape_string()?

2022-01-04 00:00:00 php mysql pdo yii mysql-escape-string

众所周知,我们不能在 Yii 等框架中使用原始 MySQL 查询.我想在 Yii 框架中运行的项目中使用 mysql_escape_string 来避免用户输入中的 SQL 注入.

As we all know, we cannot use raw MySQL queries in frameworks such as Yii. I want to use mysql_escape_string in my project which runs in Yii framework to get away from SQL injection in user input.

我知道 mysql_escape_string 在 PHP 5.5 中已被弃用,并且我有一个 PDO 替代方案.Yii框架中的替代方法以及mysql_escape_string()的PDO方式是什么?

I am aware that mysql_escape_string is deprecated in PHP 5.5 and that I have a PDO alternative. What is the alternative in Yii framework and also the PDO way of mysql_escape_string()?

推荐答案

PDO 中 mysql_escape_string 的替代方案是使用准备好的语句.以 Yii 为例:

The alternative to mysql_escape_string in PDO is using prepared statements. In Yii for example:

$user = Yii::app()->db->createCommand()
    ->select('username, password')
    ->from('tbl_user')
    ->where('id=:id', array(':id'=>$_GET['userId']))
    ->queryRow();

(来自 Yii 参考文档 http://www.yiiframework.com/doc/api/1.1/CDbCommand)

(From the Yii reference documentation http://www.yiiframework.com/doc/api/1.1/CDbCommand)

当您在准备好的语句中通过占位符传递参数时,您可以防止 SQL 注入.

You are secured you against SQL injection when you pass parameters through placeholders in a prepared statement.

相关文章