php - 使用PDO语句时,可以使用函数安全地插入变量吗?

标签 php mysql pdo

我有以下函数,它允许我对数据库执行查询(在同一类中指定)。

我需要使用bind_param函数来安全地转义这些变量吗?

如果没有,我如何将传递给函数的变量作为值分配给键?

public function query($dms, $col, $date, $ascDesc)
        {
            $this->stmt = $this->dbh->prepare("{$dms} {$col} FROM {$this->table} ORDER BY UNIX_TIMESTAMP({$date}) $ascDesc");
            $this->stmt->execute();
            return $this;
        }

最佳答案

这样你就可以使用类似的东西(记住只绑定(bind)值,而不是数组......以防数组使用 foreach 并绑定(bind)每个值):

public function query($dms, $col, $date, $ascDesc)
    {
        $this->stmt = $this->dbh->prepare("{$dms} :col FROM {$this->table} ORDER BY UNIX_TIMESTAMP(:date) :ascDesc;");
        $this->stmt->bindParam(':col', $col, PDO::PARAM_STR);
        $this->stmt->bindParam(':date', $date, PDO::PARAM_STR);
        $this->stmt->bindParam(':ascDesc', $ascDesc, PDO::PARAM_STR);
        $this->stmt->execute();
        return $this;
    }

关于php - 使用PDO语句时,可以使用函数安全地插入变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26893844/

相关文章:

php - 我的网站登录过程遇到问题

php - 如何将现有 PDO 对象注入(inject)条令实体管理器

javascript - PHP 到 JavaScript 的转换

MYSQL查询没有日期记录时返回0

mySQL 返回文本字段中的单词列表

mysql - 如何让 django 1.5 测试使用 mysql?

php - netbeans:如何调试 POST 请求 (PHP)

php - 排除字段值为空的结果

PHP、MySQL基于外部排序派优化排序

php - 当字符串无效或在数据库中找到字符串时,如何引发PDO/MySQL错误?