PDO::PARAM_INT 在 bindParam 中很重要吗?

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

在Mysql查询中添加PDO::PARAM_INTPDO::PARAM_STR有什么意义吗?

Add PDO::PARAM_INT or PDO::PARAM_STR have any meaning in Mysql query?

$sql  = 'SELECT TagId FROM tagthread WHERE ThreadId = :ThreadId';

$stmt = $this->db->prepare($sql);
$stmt->bindParam(':ThreadId', $threadid, PDO::PARAM_INT);

$stmt->execute();

推荐答案

是的,使用它.

我做了一些测试(使用 PDO::ATTR_EMULATE_PREPARES false),我发现值周围的引号会有所不同.

I did a few tests (with PDO::ATTR_EMULATE_PREPARES false) and I found out that the quotes around the values will be different.

当您使用 PARAM_INT 绑定整数值时,查询中将没有引号(带有 PARAM_INT 的字符串值有引号).如果您使用 PDO::PARAM_STR 绑定一个整数值,将会有引号,并且 mysql 必须转换为整数.

When you bind an integer value with PARAM_INT there will be no quotes in the query (A string value with PARAM_INT has quotes). If you bind an integer value with PDO::PARAM_STR there will be quotes and mysql has to cast to integer.

示例:

$stmt->bindParam(':ThreadId', $threadid, PDO::PARAM_INT);
$threadid = 123;
// SELECT TagId FROM tagthread WHERE ThreadId = 123
$threadid = '123test';
// SELECT TagId FROM tagthread WHERE ThreadId = '123test'
// mysql will cast 123test to 123

我进一步测试并阅读了该主题.结论:隐式转换是危险的,可能会导致意想不到的结果.阅读更多关于 这里.总是使用 PDO::PARAM_STR 的另一个缺点是性能.阅读有关性能的更多信息 在 Mysql 查询中引用整数的缺点?

I further tested and read on that topic. Conclusion: Implicit casting is dangerous and can lead to unexpected results. Read more on that here. Another disadvantage to always use PDO::PARAM_STR is the performance. Read more on performance Disadvantages of quoting integers in a Mysql query?

因此,如果您的列属于 [TINY|SMALL|MEDIUM|BIG]INT 类型,请使用 PARAM_INT.如果它是一个 LIMIT 子句,那么如果 PHP 中的变量类型不是整数,则它会转换为整数.

So if your column is of type [TINY|SMALL|MEDIUM|BIG]INT than use PARAM_INT. And in case it is a LIMIT clause than cast to integer if the variable type in PHP is not integer.

相关文章