- Mark Chang
- 0°C
- 5 年又 91 天
PDO bindParam 和 bindValue 差別在哪裡
首先 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
以上紀錄。
https://innstory.com/story-PDO bindParam 和 bindValue 差別在哪裡-2375
- 1,521
- 0
- 0

