2017-04-03 55 views
0

我從mysqli的語法來PDO切換並且具有一些疑惑:庫MySQLi到PDO結合參數

之前我用這個(結合INT,字符串,十進制值爲例):

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)"); 
$stmt->bind_param("sid", $firstname, $id, $value); 
$stmt->execute(); 

隨着PDO我應該使用:(這裏PARAM十進制已經犯規存在,更何況,我有寫多行暴食)

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)"); 
$stmt->bindParam(1, $firstname, PDO::PARAM_STR); 
$stmt->bindParam(2, $id, PDO::PARAM_INT); 
$stmt->bindParam(3, $value, PDO::PARAM_STR);//no decimal type! 
$stmt->execute(); 

如果我只是「忘記」關於類型和做到這一點?

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)"); 
$stmt->execute([$firstname, $id, $value]); 

int和decimal在這種情況下會失敗嗎?

+0

事情'PDO :: PARAM_'更適用於(不僅)生成正確的SQL查詢或不帶引號。並且float/decimal不能像整型'2'那樣鍵入,它們必須在真正執行的查詢中使用像'1.1'這樣的引號,所以使用'PDO :: PARAM_STR'即可。或者像你說的那樣忘記它,只使用'execute()'。 – JustOnUnderMillions

回答

0

是的,大部分時間你應該。

只有few extremely rare cases你不得不跌倒bфck來分開綁定。雖然INT和DECIMAL字符串綁定都可以。

請注意,對於小數類型,您應該在mysqli中使用「s」。

+0

如果我自己將它們投入執行,該怎麼辦? $ stmt - > execute([$ firstname,intval($ id),floatval($ value)]); – Toniq

+0

你可以,但它不會有任何區別。 –

+0

「請注意,對於小數類型,您應該在mysqli中使用」s「。」 它在這裏說'd':http://php.net/manual/en/mysqli-stmt.bind-param.php – Toniq