PHP PDOStatement:bindParam插入数据错误问题分析,开发中一定要注意
废话不多说, 直接看代码:
复制代码 代码如下:
$dbh = new PDO('mysql:host=localhost;dbname=test', "test");
$query = INSERT INTO `user` (`username`, `password`) VALUES (:username, :password);
QUERY;
$statement = $dbh->prepare($query);
$bind_params = array(':username' => "laruence", ':password' => "weibo");
foreach( $bind_params as $key => $value ){
$statement->bindParam($key, $value);
}
$statement->execute();
复制代码 代码如下:
foreach( $bind_params as $key => $value ){
$statement->bindParam($key, $value);
}
复制代码 代码如下:
//第一次循环
$value = $bind_params[":username"];
$statement->bindParam(":username", &$value); //此时, :username是对$value变量的引用
//第二次循环
$value = $bind_params[":password"]; //oops! $value被覆盖成了:password的值
$statement->bindParam(":password", &$value);
复制代码 代码如下:
$statement->bindParam(":username", $bind_params[":username"]); //$value是引用变量了
$statement->bindParam(":password", $bind_params[":password"]);
复制代码 代码如下:
foreach( $bind_params as $key => &$value ) { //注意这里
$statement->bindParam($key, $value);
}