aye.boss aye.boss - 5 months ago 9
HTML Question

Error trying to output result of calculation based on user input

I recently started PHP and I am not able to figure out how to

echo
the result of this. Any help would be appreciated.

<html>
<head>
<style>
input[type=submit]{
background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
input[type=text]{
border: 3px solid black;
}
</style>
</head>

<body>
<form action="fitness1.php" method="post">
<b>weight:</b> <input type="text" name="weight"><br>
<br>
<b>height:<b> <input type="text" name="height"><br>
<br>
<input type="submit">
</body>
</html>


This is the PHP code:

<html>
<body>
<?php

$WEight = $_Post['weight'];
$HEight = $_post['height'];

if (is_numeric($WEight)&& is_numeric($HEight)){

$bmi= $WEight / $HEight * $HEight;
}

echo ("$bmi");


else {
echo "please enter your weight and height";
}
?>
</body>
</html>

Answer

The case of variables matters in PHP. You're looking for this:

$WEight = $_POST['weight'];
$HEight = $_POST['height'];

Then, this is the logic we would use:

if (is_numeric($WEight)&& is_numeric($HEight)) {
    $bmi = $WEight / $HEight * $HEight;
    echo $bmi;
} else {
    echo "please enter your weight and height";
}

Your echo needs to be inside the if (...) { ... } block.

Edit:

As requested, here's how I would improve it:

HTML:

<html>
    <head>
        <style>
        input[type=submit]{
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 16px 32px;
            text-decoration: none;
            margin: 4px 2px;
            cursor: pointer;
        }
        input[type=text]{
            border: 3px solid black;
        }
        </style>
    </head>

    <body>
        <form action="fitness1.php" method="post" />
        <b>Weight:</b> <input type="text" name="weight" /><br />
        <br />
        <b>Height:<b>  <input type="text" name="height" /><br />
        <br />
        <input type="submit" />
    </body>
</html>

PHP:

<html>
    <body>
<?php

$weightInKg = (int) $_POST['weight'];
$heightInCm = (int) $_POST['height'];

if ($heightInCm && $weightInKg) {
    $bmi = $weightInKg / pow($heightInCm, 2);
    echo "Your BMI is ${bmi}.";
} else {
    echo "Please enter your height and weight as a number greater than 0.";
}
?>
    </body>
</html>
Comments