简体   繁体   中英

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?

Ie 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.";
    }
  }
}

You can create an array and some count variables to get success/failure count and to get which query is unsuccessful.

<?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)

Set an variable before your loop, and change it on failure. Then echo it out afterwards.

$msg = '';

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) {
                $msg = 'Fail';
            }
        } else {
            $msg = 'Nothing saved.';
        }
    }
}
if(!empty($msg)) {
    echo $msg;
}

You can use an error counter :

<?php

if(!isset($_POST["submitbutton"])) {
  echo "Click this button to save your input.";
} else {
  $errors = 0;                   //<========== ERROR COUNTER.
  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>";
        $errors++;             //<===========
      }
    } else {
      //echo "Nothing saved.";
      $errors++;               //<============
    }
  }
  if ( $errors == 0 )
       echo "Success";
  else echo "Fail";
}

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

You can have this by adding a flag.

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

The basic idea is that we are assuming that all transactions are successful while starting. Now if there is an error we set the boolean flag to false. And then finally check the status flag outside the foreach loop and print output accordingly

If you want to continue iterating through the array (ie not break ing when you encounter an error,) in general, you can do:

$failureHappened = false;

foreach($arr as $elem) {
    // do whatever with $elem to check "success" or "failure"
    if (conditional_check($elem) == true) {
        // success
    } else {
        // failure
        $failureHappened = true;
    }
}

if ($failureHappened) {
    // error handling
} else {
    // success case, if you need to do anything here
}

If $failureHappened is still false at the end of the loop, then there were no errors. If it is true , one or more errors/failures occurred. This is useful if you don't particularly care what caused the error(s), just that such error(s) occurred.

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

If I understand correctly, you wish to print 'Success' if all the queries run okay, and 'Fail' in case a query fails.

For doing this, have a temporary variable to keep track of whether some query has failed or not and use that to print. Updated code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM