在 PDO 中强类型参数的原因?

2021-12-26 00:00:00 php pdo

当您将参数绑定到 SQL 语句时,您可以提供类似 PDO::PARAM_STR 的参数类型.如果不这样做,请键入默认为 PDO::PARAM_STR.具体设置每个参数的类型可能是什么原因?PDO::PARAM_STR 可以使用任何参数,至少在 MySQL 中我知道.我认为即使使用 PDO::PARAM_STR 也可以使用 BLOB 列.

When you bind parameters to SQL statement, you can provide parameter type like PDO::PARAM_STR. If you don't, type defaults to PDO::PARAM_STR. What can be the reasons to specifically set the type of each parameter? PDO::PARAM_STR works with any parameter as I know at least in MySQL. I think even with PDO::PARAM_STR can be used even with BLOB columns.

PDO::PARAM_STR 不会引入任何 SQL 注入,因为您仍然有准备好的查询.

PDO::PARAM_STR does not introduce any SQL injection because you still have prepared queries.

推荐答案

Using PARAM_STR 碰巧总是在列值中工作,因为 mySQL 隐式地将值转换为正确的类型,但它会失败,例如在这个查询中:

Using PARAM_STR happens to always work in column values because mySQL implicitly converts values to the correct type where it can, but it will fail for example in this query:

$limit = 1;

$dbh->prepare("SELECT * FROM items LIMIT :limit");
$dbh->bindParam(":limit", $limit, PDO::PARAM_STR); 
     // Will throw "You have an error in your SQL syntax..."

绝对应该在适当的情况下使用 PARAM_INT - 对于上述情况,并为除 mySQL 之外的数据库引擎做准备,这些引擎可能对他们的期望更严格.

one should absolutely use PARAM_INT where appropriate - for cases like the one above, and to prepare for database engines other than mySQL that may be more strict in what they expect.

相关文章