PDO bindParam 和 bindValue 差別在哪裡?
Temperature: 0 °C
首先 bindParam 是綁定變數、bindValue 是綁定值。
以下範例:
bindParam
<?php
try {
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM tablename WHERE number = ?");
$stmt->bindParam(1, $test_value, PDO::PARAM_INT);
$test_value = 888;
$stmt->execute();
print_r($stmt->fetchAll());
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
執行正常。
bindValue
<?php
try {
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM tablename WHERE number = ?");
$stmt->bindValue(1, $test_value, PDO::PARAM_INT);
$test_value = 888;
$stmt->execute();
print_r($stmt->fetchAll());
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
輸出:Notice: Undefined variable: test_value
以上紀錄。