duanjianxi8439 2014-08-25 21:51
浏览 56
已采纳

PHP PDO:在一个foreach循环中绑定值,关于插入重复键更新

I'm using two foreach loops to bind the values to the positional parameters, one for INSERT INTO, the other for DUPLICATE KEY UPDATE. I was trying to reduce it to just one loop. But array_merge didn't work. Can someone tell me how can I get it done by using just one loop?

Here's an example:

  $facts = array("age","race");

  $ifield = "";
  $ufield="";
  $comma = "";
  foreach($facts as $f)
  {  
    $$f  = (isset($_POST["$f"])?$_POST["$f"]:"");
    if ($$f)
    {    
      $ifield .= $comma.$f;
      $ufield .= "{$comma}{$f} = ?";
      $comma = ",";
    }
  }

  $i = explode(',',$ifield);

  $in  = str_repeat('?,', count($i) - 1) . '?';   

  $sql .= "INSERT INTO `users` (user_id,model_no,{$ifield}) VALUES(?,?,$in)";

  $sql .= " ON DUPLICATE KEY UPDATE $ufield";

  $users = $dbh->prepare($sql);

  $user_id = $_SESSION['user_id'];
  $model_no = $_POST["model_no"];

  $users->bindValue(1,$user_id);
  $users->bindValue(2,$model_no);

  /****************************************************************/    
  $i = 3;

  foreach($facts  as $f)   
  {
    global $$f;

     if ($$f)
     {    
       $users->bindValue($i++, $$f);

     }
  }

  foreach($facts  as $f)
  {
    global $$f;

     if ($$f)
     {    
       $users->bindValue($i++, $$f);

     }
  }

  $users->execute();
  • 写回答

1条回答 默认 最新

  • dqlhsm9820 2014-08-25 21:59
    关注

    You don't need to use bound parameters in the ON DUPLICATE KEY clause. Use:

    $ufield = "$comma $f = VALUES($f)";
    

    Using VALUES(columndname) in the ON DUPLICATE KEY clause makes it use the value that would have been inserted into that column. See the documentation

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率