如何在php中清理数据以避免SQL注入


How to sanitize data in php in order to avoid SQL injection?

我已经使用了PDO:

        $stmt = $aPDO->prepare("INSERT INTO ".$this->getM_oUser()->getM_sTableName()." (email, hash_pw, hash_key) VALUES (:email, :hash_pw, :hash_key)");                                             
        $stmt->bindValue(':email', $this->getM_oUser()->getM_sEmail());
        $stmt->bindValue(':hash_pw', $this->getM_oUser()->getM_sHash_pw());
        $stmt->bindValue(':hash_key', $this->getM_oUser()->getM_sHash_Key());
        $stmt->execute();  

我还应该使用mysql_real_escape_string()来处理用户输入字符串吗?谢谢你。

使用带绑定参数的准备语句就足够了。您不需要使用mysql_real_escape_string(即使您想使用,也可能无法使用——您需要一个MySql连接资源来执行此操作)。

我会这样做,以排除许多无用的字符从您的表名:

$tableName = '`' . preg_replace('`[^-a-zA-Z0-9_]`', $this->getM_oUser()->getM_sTableName()).'`';
$stmt = $aPDO->prepare("INSERT INTO ".$tableName." (email, hash_pw, hash_key) VALUES (:email, :hash_pw, :hash_key)");