Search code examples
phpmysqlyiisql-injection

How to use mysql_escape_string() in Yii framework?


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.

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


Solution

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

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

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