David Thomas David Thomas - 7 months ago 11
PHP Question

How to access the form's 'name' variable from PHP

I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.

I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use

$_POST['variableName']
to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was used to submit the variables.

My code's below (though I'm not sure it's strictly relevant to the question):

<?php

$bmiSubmitted = $_POST['bmiSubmitted'];


if (isset($bmiSubmitted)) {
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = floor($weight/($height*$height));

?>
<ul id="bmi">
<li>Weight (in kilograms) is: <span><?php echo "$weight"; ?></span></li>

<li>Height (in metres) is: <span><?php echo "$height"; ?></span></li>

<li>Body mass index (BMI) is: <span><?php echo "$bmi"; ?></span></li>

</ul>
<?php

}

else {
?>


<div id="formSelector">

<ul>
<li><a href="#metric">Metric</a></li>
<li><a href="#imperial">Imperial</a></li>
</ul>

<form name="met" id="metric" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">

<fieldset>

<label for="weight">Weight (<abbr title="Kilograms">kg</abbr>):</label>
<input type="text" name="weight" id="weight" />

<label for="height">Height (<abbr title="metres">m</abbr>):</label>
<input type="text" name="height" id="height" />

<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />

</fieldset>

<fieldset>

<input type="reset" id="reset" value="Clear" />

<input type="submit" id="submit" value="Submit" />

</fieldset>

</form>

<form name="imp" id="imperial" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">

<fieldset>

<label for="weight">Weight (<abbr title="Pounds">lbs</abbr>):</label>
<input type="text" name="weight" id="weight" />

<label for="height">Height (Inches):</label>
<input type="text" name="height" id="height" /
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>

<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>

<?php
}

?>


I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet.

Thanks for any help and (if it's ridiculously easy) I'll flagellate myself as required.

Cheers

Answer

To identify the submitted form, you can use:

  • A hidden input field.
  • The name or value of the submit button.

The name of the form is not sent to the server as part of the POST data.

You can use code ad followed

<form name="myform" method="post" action="" enctype="multipart/form-data">
    <input type="hidden" name="frmname" value=""/>
</form>