0

I have just started learning and have put together the form below. The confusion I have is when I use empty to validate if the user selected or entered any information, the code generates the error below.

I noticed if I have the following lines of code

if(empty($gender)) {
        $errormessage[2] = "Please select your gender";
    } 

as

if(empty($_POST["gender"])) {
        $errormessage[2] = "Please select your gender";
    }

and

if(empty($gender)) {
        $errormessage[2] = "Please select your gender";
    }

as

if(empty($_POST["gender"])) {
        $errormessage[2] = "Please select your gender";
    }

I do not see the error message. I take it that error message is being generated because of the lines of code $_POST for the gender and media form elements which are radio buttons and checkboxes respectively. However if I want to initialize all the variables at the top, what is the best way to do so?

/* <?php

if(isset($_POST["submit"])) {

    $fname = $_POST["fname"];
    $lname = $_POST["lname"];
    $gender = $_POST["gender"];
    $age = $_POST["age"];
    $address = $_POST["address"];
    $media = $_POST['media'];

    $errormessage =  array();

    if(empty($fname)) {
        $errormessage[0] = "Please enter your first name";
    }

    if(empty($lname)) {
        $errormessage[1] = "Please enter your last name";
    }

    if(empty($gender)) {
        $errormessage[2] = "Please select your gender";
    }

    if(empty($age)) {
        $errormessage[3] = "Please select your age";
    }

    if(empty($address)) {
        $errormessage[4] = "Please enter your address";
    }

    if(empty($media)) {
        $errormessage = "Please select the type of media";

    }

}
?>
<html>
<head>
    <title>Sample Registration</title>
</head>
<body>
    <h2>Sample registration</h4>
        <form name="registration" method="post" action="registration.php">
            <div>
                First Name: <br />
                <input type="text" name="fname" value="">
            </div>

            <div>
                Last Name: <br />
                <input type="text" name="lname" value="">
            </div>

            <div>
                Gender: <br />
                male<input type="radio" name="gender" value="male">
                female<input type="radio" name="gender" value="female">
            </div>

            <div>
                Age: <br />
                <select name="age">
                    <option value="">Please select your age</option>
                    <option value="18-25">18-25</option>
                    <option value="26-33">26-33</option>
                </select>
            </div>

            <div>
                Address: <br />
                <textarea name="address" cols="10" rows="10"></textarea>
            </div>

            <div>
                Sign-me up: <br />
                <input type="checkbox" name="media['newsletter']" value="newsletter"> newsletter
                <input type="checkbox" name="media['specials']" value="specials"> specials
                <input type="checkbox" name="media['events']" value="events"> events

            <div>
                <input type="submit" name="submit" value="submit">
            </div>
        </form>
</body>
</html>

*/

/* Error Message */

! ) Notice: Undefined index: gender in C:\Program Files\EasyPHP-5.3.5.0\www\registration.php on line 7
Call Stack
#   Time    Memory  Function    Location
1   0.0004  341792  {main}( )   ..\registration.php:0
Dump $_SERVER

$_SERVER['REMOTE_ADDR'] =



string '127.0.0.1' (length=9)

$_SERVER['REQUEST_METHOD'] =



string 'POST' (length=4)

$_SERVER['REQUEST_URI'] =



string '/registration.php' (length=17)

Variables in local scope (#1)

$address =

    Undefined

$age =

    Undefined

$errormessage =

    Undefined

$errormsg =

    Undefined

$fname =



string '' (length=0)

$gender =

    Undefined

$lname =



string '' (length=0)

$media =

    Undefined

( ! ) Notice: Undefined index: media in C:\Program Files\EasyPHP-5.3.5.0\www\registration.php on line 10
Call Stack
#   Time    Memory  Function    Location
1   0.0004  341792  {main}( )   ..\registration.php:0
Variables in local scope (#1)

$address =



string '' (length=0)

$age =



string '' (length=0)

$errormessage =

    Undefined

$errormsg =

    Undefined

$fname =



string '' (length=0)

$gender =



null

$lname =



string '' (length=0)

$media =

    Undefined
1
  • where are you expecting the error message to show? I don't see where you are trying to display the message. Commented Apr 14, 2011 at 2:38

2 Answers 2

4

You'll want to check whether those $_POST['gender'] and $_POST['media'] variables were actually set in the HTTP POST request before you go accessing them; a better solution to initialize each $_POST var might be something like this:

$fname = isset( $_POST['fname'] ) ? $_POST['fname'] : '';

The above ternary assignment is equivalent to running the following logical expression for every single $_POST variable in which you're interested:

if( isset( $_POST['fname'] ) ) {
    $fname = $_POST['fname'];
} else {
    $fname = '';
}

If you implement either of these, you won't get a notice if you run empty() on $gender; furthermore, if $_POST['gender'] wasn't set, empty() will still behave the way you expect. It adds a little verbosity, but to rewrite your example you might try:

if( isset( $_POST["submit"] ) ) {

    $fname = isset( $_POST['fname'] ) ? $_POST["fname"] : '';
    $lname = isset( $_POST['lname'] ) ? $_POST["lname"] : '';
    $gender = isset( $_POST['gender'] ) ? $_POST["gender"] : '';
    $age = isset( $_POST['age'] ) ? $_POST["age"] : '';
    $address = isset( $_POST['address'] ) ? $_POST["address"] : '';
    $media = isset( $_POST['media'] ) ? $_POST['media'] : '';

    $errormessage =  array();
    if( empty( $fname ) )
        $errormessage[] = "Please enter your first name";
    if( empty( $lname ) )
        $errormessage[] = "Please enter your last name";
    if( empty( $gender ) )
        $errormessage[] = "Please select your gender";
    if( empty( $age ) )
        $errormessage[] = "Please select your age";
    if( empty( $address ) )
        $errormessage[] = "Please enter your address";
    if( empty( $media ) )
        $errormessage[] = "Please select the type of media";
}

Of course, you'd want to clean your data if you're going to use it in a SQL context, but that should at least get you around the error you're facing.

If you had a lot of these variables--or were repeating this task often--you might consider rolling it up into a function!

Sign up to request clarification or add additional context in comments.

16 Comments

Thanks Ryan. Considering I am new to the world of PHP, I am yet to learn about functions especially custom functions. Furthermore, I don't quite follow your example as I have no idea what ? does as well as : ''; in the code example of $fname = isset( $_POST['fname'] ) ? $_POST["fname"] : '';. Would you mind elaborating what it is and does and when I would use it?
Sure! the ?: you see there is the ternary operator in PHP and it works like this: (condition ? "true!" : "false!") for the entire expression enclosed in parentheses, if condition evaluates to true, then the whole expression evaluates to "true!"; otherwise, the whole expression evaluates to "false!"--it's really just a shortcut for if(){}else{} if you want to think of it that way
Sorry. I still don't follow. What is the condition in the code above? What are we testing as true or false?
In this code: $b = true; $val = ( $b ? "yes" : "no" );, $val == "yes", but in this code: $b = false; $val = ( $b ? "yes" : "no" );, $val == "no". Does that make more sense?
Yes it does at a very high level. Let me break it down and correct me if I am wrong. I'll use the code I was working on. $fname = ($_POST["gender"] = true ? "yes" : "no"); $fname == "yes". Is that correct? I don't still follow how this is similar with the example you gave. Sorry if I am not following as quickly.
|
2

Try using !isset() instead of empty().

As a side-note, the way you're assigning your variables will create warning notices if that $_POST value doesn't exist. If you'd like to remove those notices, use @Ryan's solution.

4 Comments

Why would I use !isset when my understanding is that all I am saying that if isset is not true, then return error message. I know that the elements are not set and returning a NULL value (I think), hence I am using empty() unless I have misunderstood the use of isset.
Example: if $_POST['blah'] doesn't exist in $_POST, then $var = $_POST['blah'] will fail and $var will not be set to anything.
Ok, if it not set to anything them empty should be able to capture the failure. Is that not right?
Technically yes, but you're still generating warning notices. They're not fatal, but they add to your error log and can result in unpredictable behavior in your script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.