在else语句中创建错误


Creating an error in an else

基本上我想添加最后一块验证,如果在项目页面上没有选择,则出现错误或用户返回到另一个页面。

当选择submit时,表单动作将其发送到确认页面,并执行下面的操作,如果有1个或多个输入,则显示所选择的项。$qty> 0),但我不知道什么放在其他部分返回一个错误或带用户回到上一页。

<?php
            $visitor = $_POST['visitor'];
            echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b>&nbsp;" . 'please confirm your purchase(s) below.' . "</p>";
            if (!($data = file('items.txt'))) {
                echo 'ERROR: Failed to open file! </body></html>';
                exit;
            }
            $total = 0;
            foreach ($_POST as $varname => $varvalue) {
                $qty = $varvalue;
                foreach ($data as $thedata) {
                    list($partno, $name, $description, $price, $image) = explode('|', $thedata);
                    if ($partno == $varname & $qty > 0) {
                        echo "<tr><td><img src='$image' width='50' height='50' alt='image'</td>
                        <td>$partno<input type='hidden' name='$partno' value=$partno></td><td>$name</td><td>&pound;$price</td>
                            <td>&nbsp;&nbsp;&nbsp;&nbsp;$qty</td><td><input type='hidden' name='visitor' value=$visitor></td>
                                <td><input type='hidden' name='qty' value=$qty></td></tr>";
                        $total = $total + $price * $qty;
                    } else {
                    }
                }
            }
            ?>

应该是这样的:

$errors = array();
foreach(...) {
   if ($partno == $varname & $qty > 0) {
      ... code for "ok" stuff
   } else {
      $errors[] = "$partno is incorrect";
   }
}
if (count($errors) > 0) {
    die("Errors: " . implode($errors));
}
... proceed to "success" code ...

基本上,对于每个失败的测试,您记录一条消息。一旦循环退出,如果有任何错误消息,您将显示它们并中止处理。如果没有错误,则继续执行其余的代码。

为什么不使用try catch块呢?

try {
    if (isset($_POST)) {
      if (!$email) {
          throw new Exception('email is not valid', 100);
      }
      // everything is good process the request
    }
    throw new Exception('Error!', 200);
} catch (Exception $e) {
    if ($e->getCode == 200) {
       // redirect
    } else {
       // do something else
    }
}

在If语句中抛出异常,然后将数据放在try/catch块中,因此如果发生错误

考虑以下方法:表单和处理表单数据的php代码都在同一个页面上。如果表单已发布,您将首先检查表单是否正常,然后对提交的数据进行处理。如果表单无效,则显示错误消息。

优点是:代码中间没有die(),没有奇怪的重定向,一切都在一个脚本中。

// simplified code in example.php
<?php
// in this variable we'll save success/error messages to print it
$msg = "";
// run this php code if the form was submitted
if(isset($_POST['submit'])) {
  // is the form valid? 
  if (strlen($_POST['username']) == 0) {
        $msg = "Please enter a username";
  } 
  else {
        // all validation tests are passed, give the user a nice feedback
       // do something with the data, e.g. save it to the db
       $msg = "Your data was saved. Have a great day";
  }
}
?>
<div class="msg"><?php print $msg; ?></div>
<form method="post">
<input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>