Search code examples
phphtmlformsundefined-index

Near identical HTML forms, one posts correct value, the other doesn't


Two of my forms on my page welcome.php are as shown:

<form action="welcomeforms.php" method="post" name="Food_Calories">
    <h4>.</h4>//spacer
    <input type="text" name="breakfast_calories" value="Calorie Amount" onFocus="this.value=''"><br>
    <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;">
</form>


<form action="welcomeforms.php" method="post" name="Foods">
    <h4>Breakfast</h4>
    <input type="text" name="breakfast" value="Add new breakfast item" onFocus="this.value=''"><br>
    <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;">
    </form>

This is the code on welcomeforms.php:

if(isset($_POST['breakfast'])){$breakfastitem = $_POST['breakfast'];}
if(isset($_POST['breakfast_calories'])){$breakfastcals = $_POST['breakfast_calories'];}
echo $breakfastitem;
echo $breakfastcals;

The forms show up correctly on the webpage, and when I enter the values 'bread' into the breakfast form and '100' into the breakfastcals form, this is what is returned on the webpage:

Undefined variable: breakfastitem in C:\wamp\www\welcomeforms.php on line 26
100

The forms are basically identical to my eye, so I don't understand why one posts the correct value and the other doesn't post anything. Is there something ridiculous that I've missed?

Thanks for any advice


Solution

  • You are using two separate forms and you can submit only one at a time. Combine them into one.

    Also instead of value="Add new breakfast item" onFocus="this.value=''" just use placeholder = "Add new breakfast item" - it will do what you intend to obtain in modern browsers - see the support: http://www.html5rocks.com/en/tutorials/forms/html5forms/#toc-other-form-attr