简体   繁体   中英

Insert Data within a loop and echo only once

i have a php script with a sql query that is inside a foreach loop and if the query succeed to run it should echo "Success" but since its inside a loop it echo "success" multiple times but i wish to only echo "success" once. I have seen other similar threads here and i have looked at those and tried solve my problem from those threads but i have not been able to solve this problem from any other threads so please dont mark this as a duplicate.

Anyway, Here is my code

<?php
session_start();
include('../../config/dbconf.php');

foreach($_POST['entry'] as $entryid) {
  $stmt = $authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");
  $stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);
  if($stmt->execute()) {
    echo "Success";
  }else{
    echo "Failed";
  }
}
?>

You could try something like this?

Also, there is no need to prepare for each iteration of the loop.

<?php
session_start();
include('../../config/dbconf.php');


$bError = false;

$authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");       

foreach($_POST['entry'] as $entryid) {   

     $stmt = $stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);

     try{

    if(!$stmt->execute()) {
      $bError = true;
      // optional break and do not process further
      // break;
      $stmt = $stmt->errorInfo()
    }

  }catch (PDOException Exception){
      $bError = true;
      // additional erorr logging here. Could add to a delimetered string to report on later   } }

echo ($bError ? 'Failure' : 'Success' );

?>

Seeing as you're not saying anything about the Failed statement, something like this might do the trick. All it requires is setting a simple flag.

<?php
session_start();
include('../../config/dbconf.php');

$feedbackGiven = FALSE;
foreach($_POST['entry'] as $entryid) {
  $stmt = $authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");
  $stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);
  if($stmt->execute()) {
    if (!$feedbackGiven)
    {
      echo "Success";
      $feedbackGiven = TRUE;
    }
  }else{
    echo "Failed";
  }
}
?>

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