require_once 'core.php' ;
try {
$db = new PDO("mysql:host=$host;dbname=$dbname",$user,$password) ;
$db -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$a = array(
'name' => 'rocky',
'password' => '12345' ,
'age' => '22'
);
$c = implode(",",array_keys($a) ) ;
$f = ":".implode(" , :",array_keys($a));
$db->beginTransaction();
$query = $db->prepare("INSERT INTO try ($c) VALUES ($f)");
foreach ($a as $key => $value) {
$query->bindParam(":".$key,$value,PDO::PARAM_STR) ;
}
$query->execute() ;
$db->commit() ;
} catch(PDOException $e){
die($e->getMessage()) ;
}
在数据库中,只有一个年龄值插入到名称、密码、年龄列中,与 22 ,22 ,22 等值相同
最佳答案
问题出在 bindParam
函数中:
$db->beginTransaction();
$query = $db->prepare("INSERT INTO try ($c) VALUES ($f)");
foreach ($a as $key => $value) {
$query->bindParam(":".$key,$value,PDO::PARAM_STR) ;
}
$query->execute() ;
$db->commit() ;
阅读bindParam
手册:
Unlike
PDOStatement::bindValue()
, the variable is bound as a reference and will only be evaluated at the time thatPDOStatement::execute()
is called.
这意味着当您执行
时 - 所有绑定(bind)变量都设置为
最后一个$value
值是数组的最后一个值,是22
。
因此,使用bindValue
:
$db->beginTransaction();
$query = $db->prepare("INSERT INTO try ($c) VALUES ($f)");
foreach ($a as $key => $value) {
$query->bindValue(":".$key, $value, PDO::PARAM_STR) ;
}
$query->execute() ;
$db->commit() ;
关于php - 数据库中所有列中仅插入一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986974/