問(wèn)題描述
在Mysql查詢中添加PDO::PARAM_INT
或PDO::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();
推薦答案
是的,使用它.
我做了一些測(cè)試(使用 PDO::ATTR_EMULATE_PREPARES false
),我發(fā)現(xiàn)值周圍的引號(hào)會(huì)有所不同.
I did a few tests (with PDO::ATTR_EMULATE_PREPARES false
) and I found out that the quotes around the values will be different.
當(dāng)您使用 PARAM_INT
綁定整數(shù)值時(shí),查詢中將沒(méi)有引號(hào)(帶有 PARAM_INT 的字符串值有引號(hào)).如果您使用 PDO::PARAM_STR
綁定一個(gè)整數(shù)值,將會(huì)有引號(hào),并且 mysql 必須轉(zhuǎn)換為整數(shù).
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
我進(jìn)一步測(cè)試并閱讀了該主題.結(jié)論:隱式轉(zhuǎn)換是危險(xiǎn)的,可能會(huì)導(dǎo)致意想不到的結(jié)果.
閱讀更多關(guān)于 這里.總是使用 PDO::PARAM_STR
的另一個(gè)缺點(diǎn)是性能.閱讀有關(guān)性能的更多信息 在 Mysql 查詢中引用整數(shù)的缺點(diǎn)?
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
類型,請(qǐng)使用 PARAM_INT
.如果它是一個(gè) LIMIT
子句,那么如果 PHP 中的變量類型不是整數(shù),則它會(huì)轉(zhuǎn)換為整數(shù).
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.
這篇關(guān)于PDO::PARAM_INT 在 bindParam 中很重要嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!