当if返回false时,如何退出if语句而不影响php的其余部分

rfbsl7qr  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(307)

//这让我快疯了。。下面要执行的代码。如果一个if语句为真,我尝试退出脚本,如果为假,则继续

<?php

require('includes/config.php');

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$selectQuery = "SELECT username, email, tokens, tokenstatus, tokensinc, tokenstatus1, tokenswith, tokenstatus2 FROM members WHERE username = '".($_SESSION['username']) ."'";

$updateQuery = "UPDATE members SET tokens=tokens - 10, tokenstatus='(Pending Tokens)' ,tokenswith=tokenswith + 10, tokenstatus1='(Pending Tokens)' WHERE username = '".($_SESSION['username']) ."'";

// Create connection
$db = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$db) {
die("Connection failed: " . mysqli_connect_error());
}

//if not logged in redirect to login page
if(!$user->is_logged_in()) { header('Location: login.php'); exit(); }

//define page title
$title = 'Withdraw ~ Pixel Jag';

//include header template
require('layout/header.php');
?>
<div class="container">
<div class="panel panel-default">
<?php

$result = mysqli_query($db, $selectQuery);

if (mysqli_num_rows($result) > 0) {
// output data of each row
echo "<ul class='list-group'>";
while($row = mysqli_fetch_assoc($result)) {

//下面的if语句是要执行的代码,如果返回true,我希望它退出脚本,如果返回false,我希望它继续更新//

if ($row['tokens'] < 10) {
        echo "<li class='list-group-item list-group-item-danger'>You do not have enough tokens!</li>";
    }
}
echo "</ul>";

}

//如果上面的返回值为false,请参阅下面我希望执行的代码//

if (mysqli_query($db, $updateQuery)) {
echo "<ul class='list-group'><li class='list-group-item list-group-item-success'><h4>Record updated successfully!</h4></li></ul>";
} else {
echo "Error updating record: " . mysqli_error($db);
}

mysqli_close($db);
?>

<div class="panel-footer">
<a href="index.php"><h4>Back To Dashboard..</h4></a>
</div>
</div>
</div>
<?php
//include header template
require('layout/footer.php');
?>
z4bn682m

z4bn682m1#

请在默认值为true的情况下添加标志$isvalid

$isValid = true;

while(mysqli_num_rows($result) > 0 || $isValid) {
     if ($row['tokens'] < 10) {
       echo "<li class='list-group-item list-group-item-danger'>You do not have  enough tokens!</li>";
         $isValid = false;
     }
}

好吧,如果这个标志是真的,那么更新一下

cu6pst1q

cu6pst1q2#

在我看来,最好的方法是,如果你在一个函数或方法中,使用一个返回;声明。

function some(){
  if(true){
  return;
  }
  else{
  //do other stuff

  if(true){
  return;
  }

}

}

但是在php中也有很多方法可以中断执行。你确实在使用其中的一些。

die;
exit;
throw new Exception('some error');//we need an exception handler in this case

然后:

if ($row['tokens'] < 10) {
        echo "<li class='list-group-item list-group-item-danger'>You do not have enough tokens!</li>";
die;// or exit or return if you are within a function o method
    }

相关问题