dragonsun2005 2016-01-25 07:13
浏览 93
已采纳

在数据库的所有列中只插入一个值

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()) ;
} 

in database only one which is age value insert in name ,password, age column same value like 22 ,22 ,22

  • 写回答

1条回答 默认 最新

  • douju5062 2016-01-25 07:42
    关注

    Problem is in bindParam function:

    $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() ;
    

    Reading bindParam manual:

    Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

    This means that when you do execute - all binded variables are set to last $value value which is the last value of array and is 22.

    So, use 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() ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭
  • ¥15 Matlab读取根元素出错