mario mario - 5 months ago 21
PHP Question

Show one message only for foreach loop

When looping through the

foreach
loop below I'll get an
echo
output for each time the loop is performed. How can I reduce these messages to only one final message?

I.e. if only
"success messages"
then echo
"Success"
, if an error occurs
("fail" or "nothing saved" message)
then echo
"Fail"
. The loop shall NOT be stopped once an error occurred but fully be proceeded. And in the end I just want to know if an error occurred or a result has not been saved.

if(!isset($_POST["submitbutton"])) {
echo "Click this button to save your input.";
} else {
foreach($_POST['tipp_id'] as $key => $tipp_id) {
if($tipp_id > 0) {
$result="
//SQL query
";
$query=mysqli_query($conn,$result);
if($query) {
echo "Success.<br>";
} else {
echo "Fail.<br>";
}
} else {
echo "Nothing saved.";
}
}
}

Answer

Every one suggested you an answer. My suggestion is below:-

<?php
$failed_query = array(); // create an empty array to get which query fails
$failed_count = 0; // count to come to know how many query failed
$success_count = 0; // count to come to know how many query succeed
if(!isset($_POST["submitbutton"])) {
  echo "Click this button to save your input.";
}else {
  foreach($_POST['tipp_id'] as $key => $tipp_id) {
    if($tipp_id > 0) {
      $result="//SQL query";
      $query=mysqli_query($conn,$result);
      if($query) { // if query runs
        $success_count++; // increase success counter
      } else {
        $failed_count++; // increase failed counter
        $failed_query[] = $result; // insert failed query to the array
      }
    }
  }
}
if($success_count > $failed_count){
    echo "final output is success";
 }else{
   echo "final output is failed";
 }
echo "query executed successfully(Number)".$success_count;
echo "query execution failed(Number)".$failed_count;
echo "Failed queries are <br/>";
echo "<pre/>";print_r($failed_query);
?>

Note:-

1.Your desired final status you will get in form of success or failed.

2.It will give you a clear picture of how many query executed successfully and how many failed.

3.Also you can check which queries failed and why(by checking failed array)