Uncaught DivisionByZeroError: Division by zero in BMI Calculator - php

I tried to make BMI Calculator using php where the student is needed to input their names, matric number, height and weight to know their BMI.
However ,I got this error
Fatal error: Uncaught Division By Zero Error: Division by zero
but it disappeared when I put the value inside.
I have no idea what's wrong with my code.
HMTL Form
<form>
Enter your name : <input type = "text" name = "student_name" value = "<?php echo #$_GET["student_name"]?>"> <!--Accepts name-->
<br>
Enter matric number : <input type = "text" name = "student_matricno" value = "<?php echo #$_GET["student_matricno"]?>"> <!--Accepts Matric Number-->
<br>
Enter weight (in KG): <input type ="text" name = "student_weight" value = "<?php echo #$_GET["student_weight"]?>"> <!--Accepts student's weight-->
<br>
Enter Height (in Meters): <input type ="text" name = "student_height" value = "<?php echo #$_GET["student_height"]?>"> <!--Accepts student's height-->
<br>
<input type = "submit">
</form>
<table> <!--Create table and display the values inputted by the user-->
<tr>
<th colspan ="2">Student Information</th>
</tr>
<tr>
<td>Name</td>
<td><?php echo #$_GET["student_name"]?></td>
</tr>
<tr>
<td>Matric Number</td>
<td><?php echo #$_GET["student_matricno"]?></td>
</tr>
<tr>
<td>Weight</td>
<td><?php echo #$_GET["student_weight"]?> kg</td>
</tr>
<tr>
<td>Height</td>
<td><?php echo #$_GET["student_height"]?> meters</td>
</tr>
</table>
PHP code
$weight = #$_GET["student_weight"];
$height = #$_GET["student_height"];
function myBMI($weight,$height) //function to calculate BMI
{ $BMI = 0;
$BMI = $weight / ($height * $height);
return $BMI;
}
$BodyMassIndex = number_format(myBMI($weight,$height),2); //convert the calculated values into 2 decimal places
//conditions for BMI
if ($BodyMassIndex < 18.5)
{
$status = "Underweight";
}
else if($BodyMassIndex < 21)
{
$status = "Normal";
}
else if($BodyMassIndex < 26)
{
$status = "Overweight";
}
else
{
$status = "OBESE";
}
echo "My BMI is" .$BodyMassIndex. "and I am ".$status;
?>
</html>```

The function does no sanity checks on the input values supplied. In the below a very simple test is done to ensure that neither value is zero (empty) and will print an alternative message if this is so. Using an elvis operator when assigning the values to $height & $weight sets them at zero if they are not present in the GET request at that stage which ensures a zero value is passed to the function.
<?php
$weight = $_GET["student_weight"] ?: 0;
$height = $_GET["student_height"] ?: 0;
function myBMI( $weight=0,$height=0 ){
return !empty($weight) && !empty( $height ) ? $weight / ( $height * $height ) : 0;
}
$BodyMassIndex = number_format( myBMI( $weight, $height ),2 );
if ($BodyMassIndex < 18.5) {
$status = "Underweight";
}else if($BodyMassIndex < 21){
$status = "Normal";
}else if($BodyMassIndex < 26){
$status = "Overweight";
}else{
$status = "OBESE";
}
if( $BodyMassIndex > 0 ) echo "My BMI is" .$BodyMassIndex. "and I am ".$status;
else echo "<span style='color:red'>Please fully complete the form to calculate your BMI</span>";
?>

Related

Increment number in php every time data is received from sql

I am trying to make a program that can get data from Sql using php. the received data is a number from 1 to 5 and each number presents a color. every time a number is received a counter adds 1 for that color in html. I have been able to code this but if the page is refreshed the counted value becomes 0.
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['name'].", ".$row['color']";
$red = "5";
$pink = "4";
$yellow = "3";
$black = "2";
$white = "1";
$colorid = $row['color'];
if ($colorid == $red){
echo "Red";
$re = 1;
$re = ++;
} elseif ($colorid == $pink){
echo "Pink";
$pi = 1;
$pi = ++;
} elseif ($colorid == $yellow){
echo "Yellow";
$ye = 1;
$ye = ++$;
} elseif ($colorid == $black){
echo "Black";
$blk = 1;
$blk = ++;
} elseif ($colorid == $white){
echo "White";
$wh = 1;
$wh = ++;
} else {
echo "Cannot verify the color code";
}
}
?>
<div>
<span>White: </span><input name="white" value="<?php echo (isset($wh))?$wh:'';?>">
<span>Black: </span><input name="black" value="<?php echo (isset($blk))?$blk:'';?>">
<span>Yellow: </span><input name="yellow" value="<?php echo (isset($ye))?$ye:'';?>">
<span>Pink: </span><input name="pink" value="<?php echo (isset($pi))?$pi:'';?>">
<span>Red : </span><input name="red" value="<?php echo (isset($re))?$re:'';?>">
</div>

Php how to echo if

Hello I have problem with PHP if else at echo part
where my echo didn't count my php result with * instead its calculate normally with variable $tot_gaji
<td align="right">
<?php
$tot_gaji = $row['gajipokok']+$rows['jlhbonus'];
if ($tot_gaji>=4500000) {
$tot_gaji+0.05*$tot_gaji;
} elseif ($tot_gaji>=5000000) {
$tot_gaji+0.15*$tot_gaji;
}
echo number_format($tot_gaji,0,".",",");
?>
</td>
If you don't assign the calculated results to the variable, it be still unchanged. So you have to assign the calculated result to a variable
<td align="right">
<?php
$tot_gaji = $row['gajipokok']+$rows['jlhbonus'];
if ($tot_gaji>=4500000) {
$tot_gaji = $tot_gaji+0.05*$tot_gaji;
// ^^^^^^^^^^^
} elseif ($tot_gaji>=5000000) {
$tot_gaji = $tot_gaji+0.15*$tot_gaji;
// ^^^^^^^^^^^
}
echo number_format($tot_gaji,0,".",",");
?>
</td>
You are not assigning the mathematics expression to any variable that's why the values of variable $tot_gai stay original
$tot_gaji = $row['gajipokok']+$rows['jlhbonus'];
if ($tot_gaji>=4500000)
{
$final = $tot_gaji+0.05*$tot_gaji;
}
elseif ($tot_gaji>=5000000)
{
$final = $tot_gaji+0.15*$tot_gaji;
}
echo number_format($final,0,".",",");
You have to assign the calculated values to $tot_gaji
$tot_gaji = $row['gajipokok']+$rows['jlhbonus'];
if ($tot_gaji >= 4500000) {
$tot_gaji = $tot_gaji+0.05*$tot_gaji;
} elseif ($tot_gaji>=5000000) {
$tot_gaji = $tot_gaji+0.15*$tot_gaji;
}
echo number_format($tot_gaji,0,".",",");
Other than not assigning your adjusted figure your second condition may not be met. i.e. a number such as 6000000 is greater than 4500000, it is also greater than 5000000, under your logic the first condition is met.
You likely want to switch your conditions or test for a range.
<?php
function adjustment($num)
{
if($num > 10) {
$num += 0.25 * $num;
} else if ($num > 5) {
$num += 0.5 * $num;
}
return $num;
}
foreach([1,6,12] as $num) {
echo adjustment($num), "\n";
}
Output:
1
9
15

PHP Self-referencing script

I am trying to embed a self-referencing PHP script inside an HTML form with following code:
Undefined index: conv
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select>
<option name = "conv" value = "f"> Fahrenheit </option>
<option name = "conv" value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
?>
</form>
And I am getting this messages:
Notice: Undefined index: conv
Notice: Undefined index: temperature2
Everything worked fine when the PHP script was in another file.
Anyone knows what am I doing wrong?
You must verify that you was send the page and $_POST exist. And correct the select element
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select name = "conv">
<option value = "f"> Fahrenheit </option>
<option value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
if(isset($_POST["temperature2"])) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
</form>
The variable ($type = $_POST["conv"];) is not set until the form is processed. Do
if (!empty($_POST["conv"])) {
$type = $_POST["conv"];
}
Here is my answer...
First, it is better to verify, is it submitted or not ??, if submit button is invoked then code proceed rest. Else you get error. Moreover result and variable will not be shown until you click the submit button.
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select name = "conv">
<option value = "f"> Fahrenheit </option>
<option value = "c"> Celsius </option>
</select>
<input type = "submit" name="submit" value = "equals">
<?php
if(isset($_POST["submit"])) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
</form>
Your PHP code will run every time you load the page, not only when someone presses submit. This means it looks out there for $_POST['conv'] and $_POST['temperature2'] but doesn't find anything because the form hasn't been posted.
You need to name your submit button and then surround all your PHP processing with an if like this:
<input type = "submit" name="mysubmit" value = "equals">
<?php
if (#$_POST['mysubmit']) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
Now it will only look at that PHP code when someone has actually submitted something. Putting the # before the #$_POST['mysubmit'] makes it so you don't get the same error that you were getting before on this new array key.

PHP: Transition from color to color in X steps

I'm looking for some code to be able to generate a list of hex colors that make up a gradient transition in PHP. For example:
function gradientColors($startHex, $endHex, $numberOfSteps) { // Code goes here }
So, if I were to call
var_dump(gradientColors('#204E32', '#224970', 9));
It would output this:
array("204E32","204D39","204C41","204C49","214B51","214A58","214A60","214968","224970");
I basically want to recreate this page:
http://www.strangeplanet.fr/work/gradient-generator/?c=9:204E32:224970
I found the solution shortly after posting the question. I guess the first hour of searching wasn't enough.
http://herethere.net/~samson/php/color_gradient/
Here is the source code from that link:
<?
$theColorBegin = (isset($_REQUEST['cbegin'])) ? hexdec($_REQUEST['cbegin']) : 0x000000;
$theColorEnd = (isset($_REQUEST['cend'])) ? hexdec($_REQUEST['cend']) : 0xffffff;
$theNumSteps = (isset($_REQUEST['steps'])) ? intval($_REQUEST['steps']) : 16;
$theColorBegin = (($theColorBegin >= 0x000000) && ($theColorBegin <= 0xffffff)) ? $theColorBegin : 0x000000;
$theColorEnd = (($theColorEnd >= 0x000000) && ($theColorEnd <= 0xffffff)) ? $theColorEnd : 0xffffff;
$theNumSteps = (($theNumSteps > 0) && ($theNumSteps < 256)) ? $theNumSteps : 16;
?>
<form method="GET">
<table border='1'>
<tr>
<td>variable:</td>
<td>number type</td>
<td>minimum</td>
<td>maximum</td>
<td>value</td>
</tr>
<tr>
<td>color begin:</td>
<td>hex</td>
<td>0x000000</td>
<td>0xFFFFFF</td>
<td><input name="cbegin" value="<? printf("%06X", $theColorBegin); ?>"></td>
</tr>
<tr>
<td>color end:</td>
<td>hex</td>
<td>0x000000</td>
<td>0xFFFFFF</td>
<td><input name="cend" value="<? printf("%06X", $theColorEnd); ?>"></td>
</tr>
<tr>
<td>number of steps:</td>
<td>dec</td>
<td>1</td>
<td>255</td>
<td><input name="steps" value="<? echo $theNumSteps; ?>"></td>
</tr>
</table>
<input type="submit" value="generate color gradient">
</form>
<?
printf("<p>values are: (color begin: 0x%06X), (color end: 0x%06X), (number of steps: %d)</p>\n", $theColorBegin, $theColorEnd, $theNumSteps);
$theR0 = ($theColorBegin & 0xff0000) >> 16;
$theG0 = ($theColorBegin & 0x00ff00) >> 8;
$theB0 = ($theColorBegin & 0x0000ff) >> 0;
$theR1 = ($theColorEnd & 0xff0000) >> 16;
$theG1 = ($theColorEnd & 0x00ff00) >> 8;
$theB1 = ($theColorEnd & 0x0000ff) >> 0;
// return the interpolated value between pBegin and pEnd
function interpolate($pBegin, $pEnd, $pStep, $pMax) {
if ($pBegin < $pEnd) {
return (($pEnd - $pBegin) * ($pStep / $pMax)) + $pBegin;
} else {
return (($pBegin - $pEnd) * (1 - ($pStep / $pMax))) + $pEnd;
}
}
// generate gradient swathe now
echo "<table width='100%' cellpadding='8' style='border-collapse:collapse'>\n";
for ($i = 0; $i <= $theNumSteps; $i++) {
$theR = interpolate($theR0, $theR1, $i, $theNumSteps);
$theG = interpolate($theG0, $theG1, $i, $theNumSteps);
$theB = interpolate($theB0, $theB1, $i, $theNumSteps);
$theVal = ((($theR << 8) | $theG) << 8) | $theB;
$theTDTag = sprintf("<td bgcolor='#%06X'>", $theVal);
$theTDARTag = sprintf("<td bgcolor='#%06X' align='right'>", $theVal);
$theFC0Tag = "<font color='#000000'>";
$theFC1Tag = "<font color='#ffffff'>";
printf("<tr>$theTDTag$theFC0Tag%d</font></td>$theTDTag$theFC0Tag%d%%</font></td>$theTDARTag$theFC0Tag%d</font></td>$theTDARTag$theFC0Tag%06X</font></td>", $i, ($i/$theNumSteps) * 100, $theVal, $theVal);
printf("$theTDTag$theFC1Tag%06X</font></td>$theTDTag$theFC1Tag%d</font></td>$theTDARTag$theFC1Tag%d%%</font></td>$theTDARTag$theFC1Tag%d</font></td></tr>\n", $theVal, $theVal, ($i/$theNumSteps) * 100, $i);
}
echo "</table>\n";
?>

PHP Forms checkbox calculation

I am trying to perform some calculations with a form but every time i try to work with checkboxes it goes wrong.
The checkboxes are beign set on value 1 in the form itselff and are being checked if there checked or not.
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0;
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
When i try to do calculations every works expect for the options with the checkboxes.
When both checkboxes (telefoon & netwerk) are selected the value should be 30.
If only one is selected the value should be 20.
But no mather what i have tried to write down it always give problem, and it always uses 20, never the value 30.
How do i solve this problem? Or suppose i am writing the syntax all wrong to lay conditions to a calculation? Any input appreciated.
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30; // never get this value, it always uses 20
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // works
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom; //prijsCom value is always wrong
Regards.
EDIT: full code below in 2 php files
<?php
if (!empty($_POST))
{
$standnaam = $_POST["standnaam"];
$oppervlakte = $_POST["oppervlakte"];
//value in the form van checkboxes op 1 zetten!
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0; //if checkbox checked value 1 anders 0
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
if (is_numeric($oppervlakte))
{
$_SESSION["standnaam"]=$standnaam;
$_SESSION["oppervlakte"]=$oppervlakte;
$_SESSION["verdieping"]=$verdieping;
$_SESSION["telefoon"]=$telefoon;
$_SESSION["netwerk"]=$netwerk;
header("Location:ExpoOverzicht.php"); //verzenden naar ExpoOverzicht.php
}
else
{
echo "<h1>Foute gegevens, Opnieuw invullen a.u.b</h1>";
}
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1">
<h1>Vul de gegevens in</h1>
<table>
<tr>
<td>Standnaam:</td>
<td><input type="text" name="standnaam" size="18"/></td>
</tr>
<tr>
<td>Oppervlakte (in m^2):</td>
<td><input type="text" name="oppervlakte" size="6"/></td>
</tr>
<tr>
<td>Verdieping:</td>
<td><input type="checkbox" name="verdieping" value="1"/></td>
<!--value op 1 zetten voor checkbox! indien checked is value 1 -->
</tr>
<tr>
<td>Telefoon:</td>
<td><input type="checkbox" name="telefoon" value="1"/></td>
</tr>
<tr>
<td>Netwerk:</td>
<td><input type="checkbox" name="netwerk" value="1"/></td>
</tr>
<tr>
<td><input type="submit" name="verzenden" value="Verzenden"/></td>
</tr>
</table>
2nd page with calculations:
<?php
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30;
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // werkt
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom;
echo "<table class=\"tableExpo\">";
echo "<th>Standnaam</th>";
echo "<th>Oppervlakte</th>";
echo "<th>Verdieping</th>";
echo "<th>Telefoon</th>";
echo "<th>Netwerk</th>";
echo "<th>Totale prijs</th>";
echo "<tr>";
echo "<td>$standnaam</td>";
echo "<td>$oppervlakte</td>";
echo "<td>$verdieping</td>";
echo "<td>$telefoon</td>";
echo "<td>$netwerk</td>";
echo "<td>$totalePrijs</td>";
echo "</tr>";
echo "</table>";
?>
Terug naar het formulier
</body>
</html>
One problem I've noticed are these lines,
if(($telefoon == 1) && ($netwerk == 1)) {
$prijsCom = 30; // will get set to 30.
}
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20; // will now be set to value of 20.
}
Here is why, if $telefoon and $netwerk are both 1, $prijsCom is set to the value of 30. It leaves that if block and goes down onto the next one, i.e.
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20;
}
It will evaluate to true since $telefoon == 1 evaluates to true and will override the value of $prijsCom to be 20.
Depending on how the code will be used, as a possible work-around, you could add the || condition first, so the value is set to 20 whether $telefoon or $netwerk is set to 1 and then check to see if they both are 1.
Update:
When looking at your code, I notice you are using $_SESSION variables, but you have not called session_start() at the beginning of the file,
<?php
session_start(); // <--you need to call this first
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
...
This may or may not be where your other problem lies, but whenever you use $_SESSION you need to call session_start first.
Call session_start(); after <?php.

Categories