PHP Self-referencing script - php

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.

Related

Uncaught DivisionByZeroError: Division by zero in BMI Calculator

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>";
?>

Calculating ideal weight, given a gender and height. How can we convert int to inches?

The calculation for the "female" option is found by multiplying her height in inches by 3.5 and subtracting 108. The calculation if "male" is selected will be found by multiplying his height in inches by 4 and subtracting 128. I am not sure how to translate this into a php function. This calculation is processed upon pushing a submit button. My goal is to calculate the ideal weight of the given gender and height.
Currently I am unable to display the $result. Does anyone see my error?
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<?php
if(isset($_POST['submit'])) {
$gender = isset($_POST['gender']) ? $_POST['gender']: 0;
$height = (int)$_POST['height'];
switch ($gender) {
case 2:
$result = ($height * 3.5) - 108;
break;
case 1:
$result = ($height * 4) - 128;
break;
default:
$result = 0;
}
echo "Ideal Weight:", $result;
}
?>
<html>
<div align="center">
<body>
<form name="form" method="post" action="<?php echo $PHP_SELF;?>">
Select Your Gender: <select name="gender">
<option value=""></option>
<option value="1">Male</option>
<option value="0">Female</option>
</select>
<br><br>
Enter Your Height: <input type="number" name="height">
<br><br>
<input type="submit" name="submit" value="Calculate"/>
</form>
</body>
</div>
</html>
Try this:
<?php
if(isset($_POST['submit'])) {
$gender = isset($_POST['gender']) ? $_POST['gender']: 0;
$height = (int)$_POST['height'];
switch ($gender) {
case 1:
$multiplier = 3.5;
$substract = 108;
break;
case 0:
default:
$multiplier = 4;
$substract = 128;
break;
}
$result = ($height * $multiplier) - $substract;
//Do whatever you want to do with $result
}
?>
This is just a rough example, conversion to inches is not done, it's only to show a way to calculate the result.
Did I understand this correctly, is this the way you want to calculate the height?
if(isset($_POST['submit'])) {
$gender = isset($_POST['gender']) ? $_POST['gender']: 0;
$height = (int)$_POST['height'];
switch ($gender) {
case 2:
$result = ($height * 3.5) - 108;
break;
case 1:
$result = ($height * 4) - 128;
break;
default:
$result = 0;
}
echo $result;
}

Using submit button to send data to PHP script

I'm making a math quiz where the user inputs their answer choice using radio buttons. I want to take the value of the radio button and compare it with the actual answer and increment score if the answer is correct.
At the moment, we are using a submit button at the bottom of the quiz where we are trying to send the data for the "check answers" script. However, I don't think any data is being pulled correctly.
Here is the code for the radio button which is from a form called "mathselect.php"
<?php //php starts here
require("opendbomath.php");
global $link, $DBname ;
if (!empty($_GET)) {
$category = $_GET["category"];
$sql = "SELECT * FROM `math`";
$result = mysqli_query($link,$sql);
$numOfQuestions = "SELECT COUNT(*) FROM `math`";
$queryNumOfQuestions = mysqli_query($link,$numOfQuestions);
if ($queryNumOfQuestions=mysqli_query($link,$sql))
{
// Return the number of rows in database
$rowcount=mysqli_num_rows($queryNumOfQuestions); //this is number of total rows
printf("Result set has %d rows.\n<br><br>",$rowcount);
}
$list = array();
$questionNumber = 0;
while (count($list) < 10){
do { //this is where we pull questions from database
$randomInt = rand(2,$rowcount); //random int is inbetween 2 and numbers of rows
$sqlselect = "SELECT * FROM `math` WHERE `bid` = \"" . $randomInt . "\" AND `acategory` = \"" . $category . "\" ";
$sqlSelectQuery = mysqli_query($link,$sqlselect);
$numOfGoodQuestions = mysqli_num_rows($sqlSelectQuery);
} while ($numOfGoodQuestions == 0); //if it returns blank field, it will loop again
if (in_array($randomInt,$list)){ //if it pulls duplicate number, continue
continue;
}
else {
//use fetch function
$row=mysqli_fetch_array($sqlSelectQuery);
$questionNumber = $questionNumber + 1;
$strQuestionNumber = (string)$questionNumber;
$slots = array();
array_push($slots,$row['aanswer']); //pushes answer choices into slots array
array_push($slots,$row['awrong1']);
array_push($slots,$row['awrong2']);
array_push($slots,$row['awrong3']);
shuffle($slots); //shuffles the answer choices
?>
<form action="mathcheck.php" method="post">
<?php
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[0]'>".$slots[0]."<br>"); //displaying 4 radio buttons with value of answer choice
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[1]'>".$slots[1]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[2]'>".$slots[2]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[3]'>".$slots[3]."<br>");
print("<br>");
}
}
//submit buton will go here
?>
<input type ="submit" value = "submit">
</form>
And also, here is the code for the "check answer" script which is called "mathcheck.php"
<?php
include('mathselect.php');
$answerChoice1 = $_POST('test1'); //pulls value of radio button
echo $answerchoice1;
$answerChoice2 = $_POST('test2');
$answerChoice3 = $_POST('test3');
$answerChoice4 = $_POST('test4');
$answerChoice5 = $_POST('test5');
$answerChoice6 = $_POST('test6');
$answerChoice7 = $_POST('test7');
$answerChoice8 = $_POST('test8');
$answerChoice9 = $_POST('test9');
$answerChoice10 = $_POST('test10');
$correctAnswer = $row['aanswer'];
$score = 0;
if ($answerchoice1 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice2 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice3 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice4 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice5 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice6 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice7 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice8 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice9 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice10 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
So, when I click on the submit button of the form, I get directed to the mathcheck script with an error. Here is the link to the quiz with the submit button for reference.
http://socialsoftware.purchase.edu/nicholas.roberts/mathquiz/mathselect.php?category=Calculus
change all of your $_POST('x') to $_POST['x']
as it stands now you are trying to access it like a function not an array.
You are loading $correctanswer once. It's not changed for every question ? SO, you need to load each answer before you do the check for that question.
You may have more problems on your code, I couldn't check everything but you may start by putting the input fields inside the form tag, i.e.:
<form action="mathcheck.php" method="post">
<?php
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[0]'>".$slots[0]."<br>"); //displaying 4 radio buttons with value of answer choice
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[1]'>".$slots[1]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[2]'>".$slots[2]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[3]'>".$slots[3]."<br>");
print("<br>");
}
}
?>
<input type ="submit" value = "submit">
</form>
Also, the correct syntax of $_POST is:
$_POST['test2'];
NOT
$_POST('test2');

Hidden HTML form fields saving the state

So I've been at this a while. Too long...
The problem I'm having is that all the hidden value fields change too the input you just put in (at least according to the source code).
This is how I’m trying to change them..(6 of these for a count, avg etc.)
<input type="hidden" name="sum" value="<?php print $sum ?>" />
This is the php file
<?php
$input = htmlspecialchars($_POST['num']);
$tempray = array($input);
//Also tried things like $sum = $sum + $input but no luck
$sum = array_sum($tempray);
$count = count($tempray);
$avg = ($sum/$count);
$max = max($tempray);
$min = min($tempray);
$posint = $poscount;
if( is_int( $input ) and $input >= 0 and $input % 2 == 0 ) {
$poscount = $poscount + 1;
}
if ($input != 0 AND $input != null){
include 'index.html.php';
}else{
include 'results/index.html.php';
}
?>
Not sure why this wouldn't work?

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