doujiunai2169 2013-01-21 20:07
浏览 20
已采纳

在循环中检查错误并执行查询?

I need to be able to check whether all elements of an array are valid before doing the queries, if I do it like this:

$arr = array(5, 3, 'test', 23, 9);
$query = $members->prepare("insert into mytable(a) values(:a)");

foreach ($arr as $val) {
    if (is_int($val)) {
       $query->execute(array(':a'=>$val));
    }
}

I only want to insert the values in the array into the database if all of them are ints, but it inserts the first two values before it gets to 'test' in the array. This is just a random example I made up for the problem that I'm having.

What would be the best way to do this?

  • 写回答

3条回答 默认 最新

  • doutuzhuohao6449 2013-01-21 20:16
    关注

    There is two ways to handel this:

    1) loop through all the values and validate it first ( you really should allays validate data that isnt controlled).

    2) If your using PDO/INNOdb start a transaction run that loop and on the fail of the validation rollback and break out of the loop.

    eg.

    $db->beginTransaction();
    $arr = array(5, 3, 'test', 23, 9);
    $query = $members->prepare("insert into mytable(a) values(:a)");
    $success = true;
    foreach ($arr as $val) {
        if (is_int($val)) {
           $query->execute(array(':a'=>$val));
        } else {
          $success = false;
          $db->rollback();
          break;
    
        }
    }
    
    if($success) {
     $db->commit();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料