loops - handle php error after foreach success -
i tried grab if crud in foreach loop, if success loop finish force message array, below function, force message after foreach correct?
// .. defined response_message array seek { foreach ($data $i => $each_data) { $sql = "update tag_0 set sequence = :sequence 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); } grab (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; homecoming $data;
$stmt->execute();
homecoming true when query succesful.
this not mean record updated , means query executed without error.
to sure, have check number of affected rows using rowcount()
try approach:
$error_counter = 0; $sql = "update tag_0 set sequence = :sequence id = :id"; $stmt = $connect_db_read->prepare($sql); foreach ($data $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 sequence id ='.$each_data['id']; array_push($response_message['success_message'], $success_message); }else{ $failed_message = 'update failed sequence id ='.$each_data['id']; array_push($response_message['fail_message'], $fail_message); $error_counter++; } }
you should prepare 1 time bind , execute in loop, no need send query db @ each iteration.
added way track variable $error_counter
if value 0
records updated.
//check after loop if($error_counter === 0){ echo 'all updates successed !!!!'; }else{ echo 'not succesful !'; }
alternatively can accomplish same using count of failed messages:
(count($response_message['fail_message'])===0)
php loops pdo foreach
No comments:
Post a Comment