在 Doctrine DBAL 中使用 executeQuery 绑定变量类型的问题

Issues binding variable types using executeQuery in Doctrine DBAL

我希望按如下方式使用 Doctrine DBAL 函数 executeQuery:

$conn = DBAL\DriverManager::getConnection($connectionParams, $config);

$sql = "SELECT count(*) FROM clients WHERE client_id = :id";

$results = $conn->executeQuery($sql, ['id' => 'foo'], ['id' => \PDO::PARAM_STR]);

var_dump($results->fetchAll());
var_dump($results->rowCount());

哪个效果很好返回:

array (size=1)
  0 => 
    array (size=1)
      'count(*)' => string '1' (length=1)
int 1

但是代码也可以使用以下行(其中类型参数声明不正确或根本没有声明):

$results = $conn->executeQuery($sql, ['id' => 'foo'], ['id' => \PDO::PARAM_INT]);

$results = $conn->executeQuery($sql, ['id' => 'foo'], ['notatag' => \PDO::PARAM_STR]);

$results = $conn->executeQuery($sql, ['id' => 'foo']);

建议声明绑定变量数据类型未被使用,引起人们对这是否受到保护以防止 SQL 注入的担忧。

我是不是做错了什么?我如何确定我的代码是安全的?

重读 DBAL 文档后我发现了这个 gem:

If you don’t specify an integer (through a PDO::PARAM* constant) to any of the parameter binding methods but a string, Doctrine DBAL will ask the type abstraction layer to convert the passed value from its PHP to a database representation.

因此,通过不定义 $types 参数,您将其留给 Doctrine 来显式转换类型。

但这有多安全? Doctrine 在描述包含 "user input in your queries":

的 "right" 方法时是这样说的

Besides binding parameters you can also pass the type of the variable. This allows Doctrine or the underlying vendor to not only escape but also cast the value to the correct type.

从安全角度建议 $types 参数是可选的。