在foreach成功之后处理php错误

时间:2014-10-23 01:49:23

标签: php loops pdo foreach

我尝试了如果在foreach循环中做CRUD,如果成功循环完成将消息推送到数组中,下面是我的函数,我在foreach之后推送消息是否正确?

// .. defined response_message array

try {
  foreach ($data as $i => $each_data) {
    $sql = "UPDATE tag_0 SET sequence = :sequence WHERE id = :id";
    $stmt = $connect_db_read->prepare($sql);
    $stmt->bindValue(':id', $each_data['id']);
    $stmt->bindValue(':sequence', $each_data['sequence']);
    $stmt->execute();
  }

  // here
  $success_message = 'success_message: store in database success';
  array_push($response_message['success_message'], $success_message);
} catch (PDOException $e) {
  $debug_message = $e->getMessage();
  array_push($response_message['debug_message'], $debug_message);
  $error_message = "error_message: ? database";
  array_push($response_message['error_message'], $error_message);
}


$data = array();
$data['response_message'] = $response_message;


return $data;

1 个答案:

答案 0 :(得分:2)

$stmt->execute();将在查询成功时返回true。

这并不意味着记录已更新,它只表示执行的查询没有错误。

要确定,您必须使用rowCount()

检查受影响的行数

尝试这种方法:

$error_counter = 0;
$sql = "UPDATE tag_0 SET sequence = :sequence WHERE id = :id";
$stmt = $connect_db_read->prepare($sql);  
foreach ($data as $i => $each_data) {
    $stmt->bindValue(':id', $each_data['id']);
    $stmt->bindValue(':sequence', $each_data['sequence']);
    $status = $stmt->execute();
    $row_count = $stmt->rowCount();
    if($status && $row_count > 0){
        $success_message = 'Successful update for sequence id ='.$each_data['id'];
        array_push($response_message['success_message'], $success_message);
    }else{
        $failed_message = 'update failed for sequence id ='.$each_data['id'];
        array_push($response_message['fail_message'], $fail_message);
        $error_counter++;
    }
}

你还应该准备一次而不是绑定并在循环中执行,不需要在每次迭代时将查询发送回db。

<小时/> 我添加了另一种跟踪变量$error_counter的方法,如果值为0,那么所有记录都会更新。

//check after the loop
if($error_counter === 0){
    echo 'All UPDATES SUCCESSED !!!!';
}else{
    echo 'NOT ALL SUCCESFUL !';
}

或者,您可以使用失败消息的计数来实现相同的目的:

(count($response_message['fail_message'])===0)