Joe Joe - 1 month ago 8
PHP Question

If first $_GET field is empty but second has a value, echo to fill in missing value

I want it to say "Please fill in the form below:" at first, before any input, but afterwards if they input an age but no name, I want it to say:
"Please enter a name:"
and if they input a name but no age then:
"Please enter your age:"
but if they submit nothing then:
"ERROR: Please enter your name AND age to continue"

Here is the code I have:

if( $_GET["name"] && $_GET["age"] ) {
echo "<p>Welcome ". $_GET['name']. " ... ";
echo "You are ". $_GET['age']. " years old.</p>";

exit();
} elseif ( $_GET["name"] == FALSE ) {
echo "<p>Please fill in the form below:</p>";
} elseif ( $_GET["age"] == FALSE ) {
echo "<p>Please fill in the form below:</p>";
} elseif ( $_GET["name"] == FALSE && $_GET["age"] ) {
echo "<p>Please fill in your name:</p>";
} elseif ( $_GET["age"] == FALSE && $_GET["name"] ) {
echo "<p>Please fill in your age:</p>";
}


I'm just learning PHP and I've tried everything I can think of, this is what I've ended up with so far!

Thank you.

Answer

Replace FALSE with empty() and you're almost there

Your form:

<form method='post' ... >
 <input type='text' name='name' value=''>
...
</form>

Then your PHP:

  if( $_POST["name"] ... ) {
  ...
  exit;
} 
elseif ( empty($_POST["name"]) ) {
       echo "<p>Please fill in the form below:</p>";
   } elseif ( empty($_POST['age'] || !is_numeric($_POST["age"]) ) {
       echo "<p>Please fill in the form below:</p>";
   } elseif ( empty($_POST['name'] && !empty($_POST['age'] ) {
       echo "<p>Please fill in your name:</p>";
   } elseif (  !empty($_POST['name'] && empty($_POST['age']) {
       echo "<p>Please fill in your age:</p>";
   }

You should really restructure your logic so that your two values are independent

  • Check if name is filled in.
  • Check if age is filled in.
  • return echo statement to user.

So the above series of elseif statements can become...

if(empty($_POST['name'])){
    $notice .= " Please enter your name.";
}
if(empty($_POST['age'])){
    $notice .= " Please Enter your age." 
}
print $notice. 

The .= concatenates the new definition on to the end of the current (or empty) value of the variable. You can print the $notice every time because it is either empty (nothing printed) or it has a value, which is something you want to print, so it's win win every time.