PHP Display Error on submission

So I made a registration form such that the user must select one of the three radio options before continuing. However if the user didn't choose an option and clicked submit I want to display at least a message that says "please choose an option" or something. Here is my code so far:

<?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";
?>

I'm having a real hard time getting the logic down to display the error message if they didn't choose an option and clicked submit.

Answers


Your setclick() function will always set $clicked to true if the form has been posted. Since you then call setclick() after your main php block, it will be true whether or not the rest of the logic has changed it. Try this:

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

and then down the bottom of the page under the form:

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

Need Your Help

Converting string to uint in actionscript / Flex

flex actionscript-3 actionscript

I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:

git svn clone fails with HTTP path not found on moved svn trunk

git-svn

I'm using git svn to access an svn repository. The svn repository was recently re-organised, with the trunk and a branch being swapped around i.e. trunk was moved to branches/old-trunk, and

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.