提交时PHP显示错误

时间:2012-09-09 03:27:56

标签: php html

所以我做了一个注册表单,以便用户必须选择三个无线电选项中的一个才能继续。但是,如果用户没有选择选项并单击提交,我希望至少显示一条消息“请选择一个选项”或其他内容。到目前为止,这是我的代码:

<?php
$reg_type = "";
function setclick()
{
    if(isset($_POST["Submit"]))
        $clicked=1;
    else 
        $clicked=0;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Reg_type"])) {
        $clicked=1;
        header('Location: Registration_1.php');
    }
    else {
        $reg_type = $_POST["Reg_type"];
        header('Location: Registration_2.php');
    }
}
echo $clicked;
?>

<form name="frmtype" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="radio" name="Reg_type" value="1"/> Registering myself with credit card or bank account <br/>
<input type="radio" name="Reg_type" value="2"/> Registering multiple people using credit card or bank account <br/>
<input type="radio" name="Reg_type" value="3"/> Registering multiple people using a purchase order <br/>
<input type="submit" name="Submit" value="Submit" />
<?php 
setclick();
if($clicked)
    echo "Please select an option";
?>

如果他们没有选择一个选项并点击提交,我很难将逻辑显示错误消息。

3 个答案:

答案 0 :(得分:1)

如果表单已发布,您的setclick()函数将始终将$clicked设置为true。既然你在主php块之后再调用setclick(),那么逻辑的其余部分是否已经改变它将是真的。试试这个:

 if(isset($_POST['Reg_type']) && $_POST['Reg_type'] != ''){ 
    $reg_type = $_POST['Reg_type'];
    header('Location: Registration_2.php');
 } else $clicked = true;

然后在表单下方的页面底部:

 if($clicked) echo "Please select an option";

答案 1 :(得分:0)

试试这个

<script>
    function checkform(){

    var checked = false;
    var buttons = document.getElementsByTagName('input')
    for (var i = 0; i < buttons.length ; i++) {
       if (buttons[i].checked) {
           checked = true;
           break;
       }
   }
   return checked;

   }
</script>

<form onsubmit="return checkform()">
<input type="radio" name="Reg_type" value="1"/> Registering myself with credit card or bank account <br/>
<input type="radio" name="Reg_type" value="2"/> Registering multiple people using credit card or bank account <br/>
<input type="radio" name="Reg_type" value="3"/> Registering multiple people using a purchase order <br/>
<input type="submit" name="Submit" value="Submit" />

Check the fiddle

这应该让你开始。请注意,此脚本按标签名称选择元素,这意味着它将获取表单中的任何输入。如果你可以使用jQuery我强烈推荐它,它将使这类任务变得微不足道。

答案 2 :(得分:0)

<?php
 $reg_type = $_POST['Reg_type'];

 if($reg_type == "1"){
       //action 1
 } else if($reg_type == "2"){
      //action 2 
 } else if($reg_type == "3") {
     //action 3 
 } else {
    // no radio button is checked. display the message

    $message = "Please select an option";
 }

?>