Php 在else中创建错误
基本上,我想添加最后一个验证,如果在items页面上没有选择任何内容,则会出现错误或用户返回到另一个页面 当选择提交时,表单操作将其发送到确认页面,并执行下面的操作,如果输入了1个或多个项($partno==$varname&$qty>0),则显示所选的项,但我不知道在else部分输入什么以返回错误或将用户带回上一页Php 在else中创建错误,php,javascript,html,Php,Javascript,Html,基本上,我想添加最后一个验证,如果在items页面上没有选择任何内容,则会出现错误或用户返回到另一个页面 当选择提交时,表单操作将其发送到确认页面,并执行下面的操作,如果输入了1个或多个项($partno==$varname&$qty>0),则显示所选的项,但我不知道在else部分输入什么以返回错误或将用户带回上一页 <?php $visitor = $_POST['visitor']; echo "<p>" . 'Hello '
<?php
$visitor = $_POST['visitor'];
echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b> " . '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>£$price</td>
<td> $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(),没有奇怪的重定向,一个脚本中的所有东西。p>
// 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>
//example.php中的简化代码
您可以重定向到标题为(“位置:)的上一页这不是一个很酷的解决方案,我将在下面发布另一种方法作为答案。我只在数据库死机或方法调用参数错误等基本问题出现时使用异常。而不是由错误的用户输入触发的错误。我只在数据库死机等基本问题出现时使用异常r使用错误的参数调用了一个方法。不是针对由错误的用户输入触发的错误。似乎无论选择了0或1或更多,始终执行else中的部分?