問題描述
我看過很多文章在使用 PDO 時(shí)在命名參數(shù)前使用冒號(hào) (:
),還有一些文章不使用冒號(hào).我會(huì)盡快不使用冒號(hào),只是因?yàn)樗倭艘粋€(gè)按鍵并且更容易閱讀.
I've seen many articles using colons (:
) in front of named parameters when using PDO, and a couple that do not use the colon. I'd just as soon not use the colon, simply because it's one less keystroke and slightly easier to read.
它似乎對(duì)我來說工作正常,但我很好奇在使用冒號(hào)時(shí)是否遺漏了一些重要的東西?
It seems to be working fine for me, but I'm curious if there is something important that I'm missing when it comes to the use of colons?
例如,這很好用:
function insertRecord ($conn, $column1, $comumn2) {
try {
$insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
VALUES(:column1, :column2)');
$insertRecord->execute(array(
'column1' => $column1,
'column2' => $column2
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
與大多數(shù)開發(fā)人員使用它相反,它也有效:
As opposed to most developers using this, which also works:
function insertRecord ($conn, $column1, $comumn2) {
try {
$insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
VALUES(:column1, :column2)');
$insertRecord->execute(array(
':column1' => $column1,
':column2' => $column2
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
注意 execute
語(yǔ)句參數(shù)中的冒號(hào).
Notice the colons in the execute
statement parameters.
我想了解冒號(hào)的用途.
推薦答案
SQL 語(yǔ)句中需要冒號(hào),以指示哪些標(biāo)識(shí)符是占位符.
Colons are required in the SQL statement, to indicate which identifiers are placeholders.
execute()
或 bindParam()
調(diào)用中的冒號(hào)是可選的.文檔指定了它們,但實(shí)現(xiàn)足夠聰明,可以弄清楚如果你不考慮它們是什么意思(你還能指什么?).
Colons in the execute()
or bindParam()
calls are optional. The documentation specifies them, but the implementation is clever enough to figure out what you mean if you leave them out (what else could you mean?).
這篇關(guān)于PDO 準(zhǔn)備好的語(yǔ)句 - 參數(shù)名稱中的冒號(hào)是做什么用的?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!