php - 我可以通过将整个 MySQL 查询作为参数传递来使用 mysql_real_escape_string 函数吗?

标签 php mysql escaping sql-injection mysql-real-escape-string

我正在努力保护一个庞大的现有应用程序免受 SQL 注入(inject)攻击。由于使用了著名的“复制/粘贴”模式开发模型,它非常古老并且几乎不可能重构。所有选择的查询参数(来自用户输入)都没有被过滤。但是,有一个正在使用的自定义查询功能。它接受 MySQL 查询作为参数并针对数据库执行它。它看起来像这样:

    public function query($sql) {
        $this->m_query_id = @mysql_query($sql, $this->m_link_id);
    ...
    }

我的问题是,会不会像这样修改:

    public function query($sql) {
        $sql = mysql_real_escape_string($sql);//escaping the whole SQL query
        $this->m_query_id = @mysql_query($sql, $this->m_link_id);
    ...
    }

根本无法工作,或者它可能会导致查询中断或返回错误数据?

示例 $sql 值可以是任何简单或复杂的 SELECT 查询,但为了示例起见,我们假设它看起来像这样:

SELECT customer_id as customerID 
FROM customers 
WHERE user_email LIKE '%some-sample-email_98@domain.com%' 
AND user_name LIKE '%La'tanya%'
AND date_registered > '2015-01-01 22:33:53'

最佳答案

感谢马克·贝克:

No you can't,nor should you.... that will escape any quotes around string literals (such as those around '%some-sample-email_98@domain.com%' ), which you don't want to do.... the best way to work with SQL isn't to escape values anyway, it's to use bind variables with prepared statements..... even if that is extra work

关于php - 我可以通过将整个 MySQL 查询作为参数传递来使用 mysql_real_escape_string 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37636126/

相关文章:

mysql - 通过检查是否为空来显示不同的文本

ruby-on-rails - 字符串 "Test ' < 3'"在我的 Rails 应用程序中显示为 "Test ' <3>"

php - Mysql "where"和 "and"语句来自多行

php - 长轮询或 Comet 如何与 PHP 配合使用?

php - MySQL/PHP 事务行为

mysql - 将 mysql 数据分布到多个磁盘

php - 在 docker 容器中安装 PHP 7 扩展

mysql - 我可以使用mysql参数 "limit start, count"

javascript - Coldfusion:空链接 href ="#"错误

PHP:序列化和反序列化包含转义字符的字符串