<?PHP
$db = new PDO($dsn,$username,$password);
$uname='avi';
$age=19;
$stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(:uname,:age)');
$stmt->execute(array(':uname'=>$uname,':age'=>$age));
$stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(?,?)');
$stmt->execute(array($uname,$age));
$stmt = $db->prepare('INSERT INTO table(uname,age) VALUES(:uname,:age)');
$stmt->bindValue(':uname',$uname); //can be $uname or just 'avi'
$stmt->binParam(':age',$uname); //cannot be 'avi' or value only
$stmt->execute();
?>
我们什么时候应该使用bindparam()?以前的所有方法似乎都更容易,并且需要更少的代码行.
使用bindparam()比其他方法(bindValue(),execute())的好处是什么?
解决方法:
bindParam()
通过引用绑定参数,因此它将在$stmt-> execute()中进行计算,这与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 test WHERE number = ?");
$stmt->bindParam(1, $xy, PDO::ParaM_INT);
$xy = 123; //See here variable is defined after it has been bind
$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 test WHERE number = ?");
$stmt->bindValue(1, $xy, PDO::ParaM_INT);
$xy = 123; //See here variable is defined after it has been bind
$stmt->execute();
print_r($stmt->fetchAll());
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
输出:
Notice: Undefined variable: xy
还有一些其他差异:
> bindparam()也有参数长度,如果你调用IN& OUT过程将输出存储回变量(也需要将带有OR语句的PDO :: ParaM_INPUT_OUTPUT附加到类型参数),它可以(必须)使用)
>使用bindparam()& bindValue()你可以指定值的类型,你不能在execute()
中做,那里一切都只是一个字符串(PDO :: ParaM_STR)