gpt4 book ai didi

php - 数据库中所有列中仅插入一个值

转载 作者:行者123 更新时间:2023-11-29 11:45:43 26 4
gpt4 key购买 nike

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 that PDOStatement::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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com