在循环中插入数据并只回显一次

cig3rfwq  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(338)

我有一个带有sql查询的php脚本,它在foreach循环中,如果查询成功运行,它应该回显“success”,但由于它在循环中多次回显“success”,但我只希望回显“success”一次。我已经看到其他类似的线程在这里,我看了这些,并试图解决我的问题,从这些线程,但我还没有能够解决这个问题,从任何其他线程,所以请不要标记为重复这个问题。
不管怎样,这是我的密码

<?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";
  }
}
?>
emeijp43

emeijp431#

你可以试试这样的吗?
而且,不需要为循环的每次迭代做准备。

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

?>
vyswwuz2

vyswwuz22#

既然你没有说任何关于失败语句的话,像这样的事情可能会起作用。它只需要设置一个简单的标志。

<?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";
  }
}
?>

相关问题