Home > Enterprise >  HTML form handling with PHP GET method
HTML form handling with PHP GET method

Time:06-28

I am new to PHP and I'm doing simple exercises to try to fully understand each thing i learn. I am confidently output data inputted from a form but for this particular exercise i can't see where I am going wrong. The form is currently outputting '1'.

I am trying to build a BMI calculator, any help is appreciated, thank you in advance.

My form

<?php
return "
<p>Calculate your BMI</p>
<form method='post' action='index.php?page=process-bmi'>
    <p>Please enter your height and weight to calculate your BMI</p>
    <label for='height'>Height</label>
    <input type='text' id='height' name='height'>
    <label for='weight'>Weight</label>
    <input type='text' id='weight' name='weight'>
    <input type='submit' value'Submit' name='bmi-submitted'>
</form>";

My php is

<?php 

$bmiSubmitted = isset($_POST['bmi-submitted']);
if ($bmiSubmitted) {
    $weight = $_POST['weight'];
    $height = $_POST['height'];
    $output = bmi($weight, $height);
}

function bmi($weight, $height) {
    $bmi = $weight/($height*$height);
    
    $response = "<p>Your bmi is $bmi</p>";
    return $response;
} 
?>

CodePudding user response:

The only missing part of your source code is to display the result using a echo statement :)

Here is your code in a one pager :

<?php 

$bmiSubmitted = isset($_POST['bmi-submitted']);

if ($bmiSubmitted) {
    $weight = $_POST['weight'];
    $height = $_POST['height'];
    $output = bmi($weight, $height);
}

function bmi($weight, $height) {
    $bmi = $weight/($height*$height);

    $response = "<p>Your bmi is $bmi</p>";

    var_dump($response);

    return $response;
} 
?>

<p>Calculate your BMI</p>
<form method='post' action='#'>
    <p>Please enter your height and weight to calculate your BMI</p>
    <label for='height'>Height</label>
    <input type='text' id='height' name='height'>
    <label for='weight'>Weight</label>
    <input type='text' id='weight' name='weight'>
    <input type='submit' value'Submit' name='bmi-submitted'>
</form>

And here is the output when I did the test with 167 cm height and 90 kg weight :

enter image description here

If the inputs are 167 and 90 instead of 1.67 and 90, you get this result :

Your bmi is 0.0032270787765786

rounded up to 1...

Body Mass Index is a simple calculation using a person's height and weight. The formula is BMI = kg/m2 where kg is a person's weight in kilograms and m2 is their height in metres squared

So 1.67 meters is better than 167 meters to get a good result ;)

  • Related