这可以吗?
$error_msg = "";
if(!isset($_POST["name"]) || empty($_POST["name"])) {
$error_msg="Not set name";
exit();
} else if(!isset($_POST["radio1"]) || empty($_POST["radio1"])) {
$error_msg="Not set question1";
exit();
} else if(!isset($_POST["radio2"]) || empty($_POST["radio2"])) {
$error_msg="Not set question2";
exit();
} else { //... some code here }
//continues here after exit???
//Somewhere code printing first cahched error message
我不确定exit()的行为。我想要做的是当我达到第一个条件失败时,我设置$ error_msg并退出if,否则if,else阻止并继续执行后,我在行上标记“在退出后继续这里???”我在哪里打印错误信息并做其他事情,比如打印表格等。
修改 对于反应 - 我有点认为它可能会结束剧本但是。所以我知道我错了,但我的问题实际上是关于如何做以结束“if else block”。什么对我有用?像休息,返回的东西? 如果如果没有设置名称和radio2,则错误消息将是“未设置问题2”而不仅仅是“未设置名称”,因为我只想首先发生错误。
答案 0 :(得分:5)
无需exit()
全部删除它们。没有必要“结束”if else块。一旦满足任何条件,它就会结束。
$error_msg = "";
if(!isset($_POST["name"]) || empty($_POST["name"])) {
$error_msg="Not set name";
} else if(!isset($_POST["radio1"]) || empty($_POST["radio1"])) {
$error_msg="Not set question1";
} else if(!isset($_POST["radio2"]) || empty($_POST["radio2"])) {
$error_msg="Not set question2";
} else {
// Code to run if all post variables are set correctly.
}
if (!empty($error_msg)) {
// Display error message - echo $error_msg;
}
答案 1 :(得分:0)
exit()
将结束PHP脚本的其余部分,您不需要在此上下文中使用它。
如果上面的条件失败,if语句将只处理else
和else if
有关exit()
:PHP.net Exit()