Failure to display $result of a calculation - php

Here we are calculating a person's ideal weight ($result) based off of their selected gender ($gender) and their inputted height ($height).
For some reason, I am unable to see the echoed $result from the calculation.
Anyone have any clues as to why I cannot see this result?
<?php
if(isset($_POST['Submit'])) {
$gender = $_POST['selectedGender'];
$height = $_POST['patientHeight'];
$result;
if ($gender == "Male") {
$result = ($height * 4) - 128;
echo $result; }
else if ($gender == "Female") {
$result = ($height * 3.5) - 108;
echo $result; }
}
?>
<html>
<div align="center">
<body>
<form name="form" method="post" action="<?php echo $PHP_SELF;?>">
Select Your Gender: <select name="selectedGender">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<br><br>
Enter Your Height: <input type="number" name="patientHeight" placeholder="Units are in Inches">
<br><br>
<input type="submit" name="Submit" value="Calculate Your Ideal Weight"/>
</form>
</body>
</div>
</html>

Your use of if / else if isn't the best way to do this. You should be using a switch/case call.
switch($gender) {
case "Male":
$result = ($height * 4) - 128;
break;
case "Female":
$result = ($height * 3.5) - 108;
break;
default: // notice the 'default' here?
$result = 'derp'; // that will set it always.
break; // meaning if you don't have a value present.
}
echo $result;
The above will cover all results, including the one where $gender isn't set.
As noted in other answers, there is no such variable called $PHP_SELF, you'll find that in server super global - $_SERVER['PHP_SELF'].

I noticed that there is an empty radio button with the name selectedGender. If this is passed to the form, the if else if statement will not catch it, and not echo anything.
Maybe take out that empty radio button, or add a final else statement.

Your echo is above <html>. This code will calculate the weight and render it in a javascript alert:
<?php
if(isset($_POST['Submit'])) {
$gender = $_POST['selectedGender'];
$height = $_POST['patientHeight'];
$result;
if ($gender == "Male") { $result = ($height * 4) - 128; }
else if ($gender == "Female") { $result = ($height * 3.5) - 108; }
$msg = 'As a '.$gender.' '.$height.' inches tall your weight should be '.$result.' pounds.';
echo '<Script language="javascript">alert("'.$msg.'");"</script>';
}
?>

Related

Focus on HTML Select dropdown option after GET request

So I am making a programme and I am submitting a form to itself. This programme is a very basic calculator as I am new to HTML and PHP. I am trying to make it so that when you submit the form, the Select dropdown will remain on the most recently used operator.
For example, if I make the calculator do '5 + 5', then I want the submitted form to keep the operator dropdown on '+'.
Here is my code:
<?php
// grab the form values from $_HTTP_GET_VARS hash extract($_GET);
// first compute the output, but only if data has been input if(isset($calc) && $operator == "multiply") { // $calc exists as a variable
$prod = $x * $y; } elseif (isset($calc) && $operator == "plus") {
$operator = $plus;
$prod = $x + $y; } elseif (isset($calc) && $operator == "minus") {
$operator = "minus";
$prod = $x - $y; } elseif (isset($calc) && $operator == "divide") {
$sign = "/";
$prod = $x / $y; } else { // set defaults
$x=0;
$y=0;
$prod=0; } ?>
<html> <head>
<title>PHP Calculator Example</title> </head>
<body>
<h3>PHP Calculator (Version 1)</h3>
<p>Multiply two numbers and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<label for="x">x = </label>
<input type="text" name="x" id="x" size="5" value="<?php print $x; ?>"/>
<select name="operator" id="operator">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">*</option>
</select>
<label for="y">y = </label>
<input type="text" name="y" id="y" size="5" value="<?php print $y; ?>"/>
<input type="submit" name="calc" value="Calculate"/>
</form>
<!-- print the result -->
<?php if(isset($calc)) {
print "<p>x $sign y = $prod</p>";
} ?>
</body> </html>
In order to remain on option selected in the select element
The option has to have an attribute "selected"
<select name="operator" id="operator">
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "plus"){echo "selected";} ?> value="plus">+</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "minus"){echo "selected";} ?> value="minus">-</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "divide"){echo "selected";} ?> value="divide">/</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "multiply"){echo "selected";} ?> value="multiply">*</option>
</select>
Hope that it will help you.
A possible solution employing javascript would be this
<?php
if(isset($_GET['operator'])) {
?>
<script>document.getElementById("operator").value = '<?=$_GET['operator']?>';</script>
<?php
}
?>

if statement error showing different values

I am newbie to PHP and I am trying to study "if statement" by making calculator and I end up with an error.the result showing is not correct and also please help to suggest how to clear input after each submission.
<html !doctype>
<head>
<title>
</title>
</head>
<body>
<?php
error_reporting();
if(isset($_POST['submit'])) {
$num1 = $_POST['number1'];
$num2 = $_POST['number1'];
$action = $_POST['action1'];
if($action == "addition"){
$add = $num1 + $num2;
echo "your value is";
echo $add;
}
if($action == "subtraction"){
$sub = $num1 - $num2;
echo "your value is";
echo $sub;
}
if($action =="multipilcation"){
$multi = $num1 * $num2;
echo "your value is";
echo $multi;
}
if($action =="division"){
$divi = $num1 / $num2;
echo "your value is";
echo $divi;
}
}
?>
<form method='post' name='myform'>
Enter Number 1:<br>
<input type="number" name="number1" >
<br>
Enter Number 2:<br>
<input type="number" name="number2" >
<br>
choose operation<br>
<select name='action1'>
<option>addition</option>>
<option>subtraction</option>
<option>multipilcation</option>
<option>division</option>
</select>
<input type="submit" name="submit" value="submit">
</form>
</body>
<footer>
</footer>
</html>
You used same number1 for two variables, change it to number2
$num1 = $_POST['number1'];
$num2 = $_POST['number2'];
^
$action = $_POST['action1'];
1) You are not passing any value in <option></option> tag.
<select name='action1'>
<option value="addition">addition</option>>
<option value="subtraction">subtraction</option>
<option value="multipilcation">multipilcation</option>
<option value="division">division</option>
</select>
2) Change $num2 = $_POST['number1']; to $num2 = $_POST['number2'];
<?
if(isset($_POST['submit'])) {
$num1 = $_POST['number1'];
$num2 = $_POST['number2'];
$action = $_POST['action1'];
$num2 = $_POST['number1'];
chnage with:
$num2 = $_POST['number2'];
Also add value attribute for option tag inside select.
<option value="addition">addition</option>>
<option value="subtraction">subtraction</option>
<option value="multipilcation">multipilcation</option>
<option value="division">division</option>

if elseif php simple calculator

This is form for calculator
<form method='post' action='result.php' name='calc_form'>
<input type='text' name='input1' size='15'>
<select name='operation'>
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multi">*</option>
<option value="invalid">**</option>
<option value="divide">/</option>
</select>
<input type='text' name='input2' size='15'>
<input type='submit' value='go'>
</form>
This is php with if elseif statement
<?php
define ('INVALID_INPUT', 'ERROR: invalid input');
define ('INVALID_OPERATOR', 'ERROR: invalid operator');
$result = null;
if
(isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$operation = $_POST['operation'];
switch ($operation)
{
case 'plus':
$result = $input1 + $input2;
break;
case 'minus':
$result = $input1 - $input2;
break;
case 'multi':
$result = $input1 * $input2;
break;
case 'divide':
$result = $input1 / $input2;
break;
default:
$result = INVALID_OPERATOR;
break;
}
}
elseif
(!isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
$result = INVALID_INPUT;
}
if ($result !== null)
{
echo <<<EOM
<h2>you calculate</h2> $input1
<h2>and</h2> $input2
<h2>result is:</h2>
$result
EOM;
}
?>
I even tried with only else statement and without condition but it wont show INVALID INPUT when nothing is added in form. What is wrong here?
The problem is with this piece of code:
if
(isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
Even if a user enters nothing in the input fields, they will still pass isset($_POST['input1']), since they are 'set' to an empty string. Try switching it to this instead:
if
(isset($_POST['input1']) && strlen($_POST['input1']) &&
isset($_POST['input2']) && strlen($_POST['input2']) &&
isset($_POST['operation']))
You could just use an else statement instead of an else if statement. That way if you change the inputs you don't have to list each of them twice.
eg:
if (isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation']))
{
// result = calculation
} else
{
// result == code
}
Try this - I tested this on my server and it works!
calculator.php
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);;
define ('INVALID_INPUT', 'ERROR: invalid input');
define ('INVALID_OPERATOR', 'ERROR: invalid operator');
$input1 = $input2 = $operation = null;
if (isset($_POST['input1']) and isset($_POST['input2']) and isset($_POST['operation']))
{
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$operation = $_POST['operation'];
if(is_numeric($input1) and is_numeric($input2))
{
switch ($operation)
{
case 'plus':
$result = $input1 + $input2;
break;
case 'minus':
$result = $input1 - $input2;
break;
case 'multi':
$result = $input1 * $input2;
break;
case 'divide':
$result = $input1 / $input2;
break;
default:
$result = INVALID_OPERATOR;
break;
}
}
else
{
$input1 = '';
$input2 = '';
$operation = 'invalid';
$result = INVALID_INPUT;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="">
<form method='POST' action='calculator.php'>
<input type='text' name='input1' size='15' value="<?php echo $input1; ?>">
<select name='operation'>
<option <?php if($operation == 'plus') { echo 'selected';} ?> value="plus">+</option>
<option <?php if($operation == 'minus') { echo 'selected';} ?> value="minus">-</option>
<option <?php if($operation == 'multi') { echo 'selected';} ?> value="multi">*</option>
<option <?php if($operation == 'invalid') { echo 'selected';} ?> value="invalid">**</option>
<option <?php if($operation == 'divide') { echo 'selected';} ?> value="divide">/</option>
</select>
<input type='text' name='input2' size='15' value="<?php echo $input2; ?>">
<span>=</span>
<input type='text' name='result' size='50' value="<?php echo $result; ?>">
<input type='submit' value='go'>
</body>
</html>
Your condition is wrong; this is impossible:
!isset($_POST) and
isset($_POST['input1']) and
isset($_POST['input2']) and
isset($_POST['operation'])
I suspect you mean
!isset($_POST) or
!isset($_POST['input1']) or
!isset($_POST['input2']) or
!isset($_POST['operation'])

How to validate form input on the same page by using random numbers?

Would be awesome if you could help me out! I am trying to build a simple page to display random math questions. The answers should be typed in by the user and should be validated on the same page, giving him feedback on success and failure.
The problem is that by submitting the form input to the same page (I called it "form6.php") the page reloads and a new set of numbers is generated - that is why the "solution" variable is newly defined and cannot be used to test the accuracy of the user's answer.
This is the code I have so far (works fine for fixed numbers but fails with the random number generation):
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$solution = $number1+$number2;
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer'])){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>
Any help is highly appreciated! Since I am not a professional coder, the more specific you can get, the better!
A POSTed form will reload your PHP script, causing 2 new rand() numbers to be generated. You're going to want to pass the solution in the form.
Edit: I updated the answer to show a quick solution for using random operands for verification. This was simply done by switching through a random integer. Please note that when using - or / you may receive non-integer numbers (3 / 58 or 15 - 86), so you may want to add some custom logic to prevent this.
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
switch(rand(0,3)) {
case 0:
$solution = $number1 + $number2;
echo "$number1+$number2=?";
break;
case 1:
$solution = $number1 - $number2;
echo "$number1-$number2=?";
break;
case 2:
$solution = $number1 * $number2;
echo "$number1*$number2=?";
break;
case 3:
$solution = $number1 / $number2;
echo "$number1/$number2=?";
break;
}
?>
<form action="form6.php" method="post">
Your Answer:<br><input type="integer" name="answer">
<input type="hidden" name="solution" value="<?php echo $solution; ?>">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
if ($_POST["answer"] == $_POST['solution']) {
// Valid
} else {
// Incorrect
}
}
?>
If you don't want to include the solution in your form (be it hidden), you have to store solutions in a separate text file in which you can, for instance, serialize your data.
Alternatively, you can use sessions or cookies.
But you have to store the solution somewhere.
Here is an attempt with sessions:
<?php
session_start();
$nb1 = rand(1,100);
$nb2 = rand(1,100);
$_SESSION['number1'] = $nb1;
$_SESSION['number2'] = $nb2;
$_SESSION['solution'] = $nb1 + $nb2;
// (...)
if(isset($_POST['answer']))
{
if ($_POST["answer"] == $_SESSION['solution'])
{echo "That's right";}
else
{echo "That's wrong!";};
unset($_SESSION['nb1']);
unset($_SESSION['nb2']);
unset($_SESSION['nbsolution']);
}
if(isset($_POST['answer'])===true){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
If you are using isset($_POST['answer']) you must include === true at the end
Also make sure you use instead of integer.
#user3261573,
As pointed out by #Sam, you could pass the value in a hidden field, but, as #Jivan said, a better approach would be using a session to store the solution.
Here's the code:
Ps.: I simplified the code for a better understanding.
<?php
// Initiate session
session_start();
// If the FORM has been submited, verify answer
if( isset($_SESSION['solution']) === TRUE && $_SESSION['solution'] !== NULL && isset($_POST['answer']) === TRUE && isset($_POST['solution']) == TRUE ){
if( $_SESSION['solution'] == $_POST['answer'] ){
echo 'That\'s right';
}else{
echo 'That\'s wrong';
}
}
// If the FORM ain't submited yet, display the question
else{
// Random numbers
$number1 = rand(1,100);
$number2 = rand(1,100);
// Store solution in session for further comparison
$_SESSION['solution'] = $number1+$number2;
// Echo question
echo "$number1+$number2=?";
echo '<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>';
}
?>
If you like it, here's a few tutorials on using PHP SESSIONs:
http://www.w3schools.com/php/php_sessions.asp
http://www.php.net/manual/en/session.examples.basic.php
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
<input type="hidden" name="n1" value="$number1">
<input type="hidden" name="n2" value="$number2">
</form>
<?php
if(isset($_POST['answer'])){
$solution = $_POST['n1'] + $_POST['n2'];
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>

Calculator selection stays after submit

Hello i'm trying to make a calculator.And i have this problem : I'm tryng to make the selection that i made it to stay after submit. I've found some code on google for my selection to stay after submit but my calculator won't work anymore. Can you help me ?
here is the code when my calculator works but my selection doesn"t stays after submit
<html>
<body>
<center>
<form method="post">
Food:
<Select name="Dropdown"><br>
<option>Cheese</option>
<option>Apple</option>
<option>Egg</option>
</select>
</br>
Amount:
<input name="amount" type="text">grams<br><br>
<br><input type="Submit" value="Calculate">
<br><br>
<?php
$result=$_POST['result'];
$Dropdown=$_POST['Dropdown'];
$amount = $_POST['amount'];
switch ($Dropdown){
case 'Cheese':
$result= (7.74 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Apple':
$result= (1.94 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Egg':
$result= (13.74 * $amount) / 100;
echo "<p> $result </p>";
}
?>
</form>
</center>
</body>
</html>
and here is my code when my slection stays after submit but my calculator won't work
<html>
<head></head>
<body>
<center>
<?php
if (!empty($_POST['Dropdown'])) {
$dropDownVal = $_POST['Dropdown'];
} else {
$dropDownVal = 1;
}
?>
<form method="post">
<select name="Dropdown" >
<option value="1" <?php if ($dropDownVal==1) echo 'selected="selected"'; ?>>Cheese </option>
<option value="2" <?php if ($dropDownVal==2) echo 'selected="selected"'; ?>>Apple</option>
<option value="3" <?php if ($dropDownVal==3) echo 'selected="selected"'; ?>>Egg</option>
</select>
<?php
$result=$_POST['result'];
$Dropdown=$_POST['Dropdown'];
$amount = $_POST['amount'];
switch ($Dropdown){
case 'Cheese':
$result= (7.74 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Apple':
$result= (1.94 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Egg':
$result= (13.74 * $amount) / 100;
echo "<p> $result </p>";
}
?>
<input name="amount" type="text">grams<br><br>
<br><input type="Submit" value="Calculate">
</form>
</center>
</body>
</html>
Thanks
What you receive back in the $_POST['Dropdown'] is the value not the content so you will get 1 or 2 or 3 and not the Cheese or Apple or Egg.
So try:
switch ($Dropdown){
case 1: // Cheese
$result= (7.74 * $amount) / 100;
break;
case 2: //Apple
$result= (1.94 * $amount) / 100;
break;
case 3: // Egg
$result= (13.74 * $amount) / 100;
break;
default:
$result = 0;
}
echo "<p> $result </p>";
?>
In future if you are not sure what is in a variable that is returned from the user do a
echo '<pre>' . print_r( $_POST, TRUE ) . '</pre>';
to get a nice display of the array on the browser.
Or a
var_dump( $var );

Categories