How to display answer to a form? - php

If im trying to post the answer on the same page would it look something like this? Not too sure whether I have used the correct functions, please check my code:
<form method="post" action="activity.php">
<input type="text" name= "num1" value="Enter a number"/>
<select name= "conversion">
<option>Select a conversion</option>
<option name="lb to kg">lbs to kgs</option>
<option name="kgs to lbs">kgs to lbs</option>
<option name="cm to in">cms to inchs</option>
<option name="inchs to cms">inchs to cms</option>
<option name="pints to litres">pints to litres</option>
<option name="litres to pints">litres to pints</option>
<option name="faranheit to centigrade">faranheit to centigrade</option>
<option name="centigrade ti faranheit">centigrade to faranheit</option>
</select>
<input type="submit" value="convert" />
</form>
Then the php after the form:
$num1 = $_GET["num1"];
$conversion = $_POST["conversion"];
if($conversion == "lbs to kgs")
{
$answer_lb = $num1 * 0.45;
echo $answer_lb;
}
if($conversion == "kgs to lbs")
{
$answer_kg = $num1 * 2.2;
echo $answer_kg;
}
if($conversion == "cms to inchs")
{
$answer_inch = $num1 * 2.54;
echo $answer_inch;
}
if($conversion == "inchs to cms")
{
$answer_cm = $num1 * 0.393;
echo $answer_cm;
}
if($conversion == "pints to litres")
{
$answer_pints = $num1 * 0.568;
echo $answer_pints;
}
if($conversion == "litres to pints")
{
$answer_litres = $num1 * 1.579;
echo $answer_litres;
}
if($conversion == "faranheit to centigrade")
{
$answer_faranheit = ($num1 - 32) * (5/9);
echo $answer_faranheit;
}
if($conversion == "centigrade to faranheit")
{
$answer_centigrade = ($num1 * 9/5) + 32;
}
?>
<em>
I wasnt sure whether or not the php code has to come before or after the form and was unsure about the form action.

//EDITED the answer according to your needs:
Here's a working example of the code below: http://codepad.viper-7.com/vu6j0N
<?php
$calculation_models = array();
$calculation_models[] = array('description'=>'lb to kg',
'calculation' => function($val) { return $val * 0.45; }
);
$calculation_models[] = array('description'=>'kgs to lbs',
'calculation' => function($val) { return $val * 2.2; }
);
$calculation_models[] = array('description'=>'cm to in',
'calculation' => function($val) { return $val * 2.54; }
);
$calculation_models[] = array('description'=>'inchs to cms',
'calculation' => function($val) { return $val * 0.393; }
);
$calculation_models[] = array('description'=>'pints to litres',
'calculation' => function($val) { return $val * 0.568; }
);
$calculation_models[] = array('description'=>'litres to pints',
'calculation' => function($val) { return $val * 1.579; }
);
$calculation_models[] = array('description'=>'faranheit to centigrade',
'calculation' => function($val) { return ($val - 32) * (5/9); }
);
$calculation_models[] = array('description'=>'centigrade to faranheit',
'calculation' => function($val) { return ($val * 9/5) + 32; }
);
if (isset($_GET['val']) && isset($_GET['model'])) {
$result = $calculation_models[$_GET['model']]['calculation']($_GET['val']);
echo 'The result is ' . $result;
}
?>
<!-- build the form dynamically from the array above -->
<form method="get" action="#">
<input type="text" name="val" placeholder="Enter a number"/>
<select name="model">
<?php foreach($calculation_models as $key => $model) : ?>
<option value="<?php echo $key; ?>"><?php echo $model['description']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="convert" />
</form>

if you are asking this question, then it is not exactly simple. To change the content of the page without reloading a new page usually involves a technique known as AJAX,
basically, it uses javascript to submit the request, and javascript will again process the response after it is received.

I assume you have to files like: calculator.html and calculator.php
calculator.html is the form.
The first solution to make the result display on the same page is simple:
put everything into caclculator.php like this
<?php
if($_GET["submit"]){
#your code
}
?>
<html>
<!-- your html -->
</html>
If this was not what you asked for, the next method is using an iframe "with the result" and javascript to send your data to the iframe.
And the last solution is plain-ajax.

Related

php how to do a loop to calculate score for a quiz website

i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission

How can I simplify this PHP script?

I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

Search filters not functioning on first attempt

I have a search filter based on flags of different colors.
If I will search based on color it is showing result but when I will select white color flag it is showing entire data in my database table. But If I choose any other color apart from white color for the first time it will show result. And if I choose white color flag second time,then it gives the correct result. What might be the reason. I need help
//filter on flag_color
if($this->input->get('flg')){
$arr_flag = explode('-', $this->input->get('flg'));
$str_flag = implode(',',$arr_flag);
if(6 == $str_flag){
$str_flag = 0;
}
$str_condition .= 'AND t.sender_flag_color_id IN('.$str_flag.')';
}
array(
'0'=>array(
'color'=>'White',
'path'=>'whiteflag.png'),
'1'=> array(
'color'=>'Blue',
'path'=>'blueflag.png'),
'2'=>array(
'color'=>'Green',
'path'=>'greenflag.png'),
'3'=>array(
'color'=>'Yellow',
'path'=>'yellowflag.png'),
'4'=>array(
'color'=>'Red',
'path'=>'redflag.png') ,
'5'=>array(
'color'=>'Orange',
'path'=>'orangeflag.png')
);
view
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
if(isset($arr_params['flg']))
{ ?>
<input type="hidden" id="flag_in_url" name="flag_in_url" value="yes" />
<?php
}
?>
<!-- id="webmenu1" -->
<select class="flag_color" onchange="urgency_select('flag_color')" name="header_flag" id="webmenuflag1">
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
$int_flag_url = '';
if(isset($arr_params['flg']))
{
$int_flag_url = $arr_params['flg'];
}
if(isset($arr_flag_color))
{
foreach($arr_flag_color as $key=>$flag_color)
{
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
else
{
$flag_selected = '';
}
?>
<option <?php echo $flag_selected;?> value="<?php echo $key;?>" data-image="<?php echo base_url();?>images/<?php echo $flag_color['path'];?>"></option>
<?php
}
}
?>
js: urgency_select
var flag_color_id = '';
if(select_option == 'flag_color' || $( "#flag_in_url" ).val() == 'yes')
{
if($( ".flag_color" ).val() != undefined)
{
var flag_color_id = $( ".flag_color" ).val();
if(flag_color_id == 0)
flag_color_id = 6;
search_url += 'flg/'+flag_color_id+'/';
}
}
Its because conflict with the value of white color flag...
In the view I changed the code
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
to
if($int_flag_url == 0 || $int_flag_url == $key)
{
$flag_selected = 'selected';
}

Shopping cart code is not working. getting error for undefined variable

I found this tutorial on making a shopping cart app and It's not working. I get an error about undefined variable bookFound on line 22 where it says if(!$bookFound). I see maybe why it is not defined, I'm thinking maybe because it was defined in the if statement previously in the code and that is not returning true. Any ways I'm having problems fixing it so if you can make this code work that will be great. The user should be able to click the button and the div should be updated with calculated results.
<?php
session_start();
$booksInfo = $_SESSION['cart'];
if(count($booksInfo) > 0)
{
$bookFound = false;
for($i=0; $i< count($booksInfo); $i++)
{
if($booksInfo[$i]['bookId'] == $_POST['bookId'])
{
$booksInfo[$i]['quantity'] = $_POST['quantity'];
$bookFound = true;
break;
}
}
}
if(!$bookFound) //line 22 where error was found
{
$book = array('bookId' => $_POST['bookId'], 'quantity' => $_POST['quantity']);
array_push($booksInfo, $book);
}
$_SESSION['cart'] = $booksInfo;
$grossTotal = 0;
for($i=0; $i< count($booksInfo); $i++)
{
$aBook = $booksInfo[$i];
$bookName = getBookName($booksInfo[$i]['bookId']);
$bookPrice = getPriceForBook($booksInfo[$i]['bookId']);
$totalPrice = $bookPrice * $booksInfo[$i]['quantity'];
$grossTotal+= $totalPrice;
$str.= '<strong>Name - </strong>'.$bookName;
$str.= '<br/>';
$str.= ' <strong>Copies - </strong>'.$booksInfo[$i]['quantity'];
$str.= '<br/>';
$str.= '<strong>Price - </strong>$'.$bookPrice. ' * ' .$booksInfo[$i]['quantity'].' = $'.$totalPrice;
$str.= '<br/><br/>';
}
$str.= '<strong>Net Amount - </strong>$'.$grossTotal;
echo $str;
function getBookName($id)
{
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
if($book['id'] == $id)
{
return $book->name;
}
}
return false;
}
function getPriceForBook($id)
{
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
if($book['id'] == $id)
{
return $book->price;
}
}
return false;
}
?>
Index:
<body>
<div class="cart">
<strong>Your cart</strong>
<p id = "cart">Cart is empty</p>
</div>
<?php
$objXML = simplexml_load_file('books.xml');
foreach($objXML->book as $book)
{
echo '<div>';
echo 'Name - ' . $book->name, '<br />';
echo 'price - $'. $book->price, '<br/>';
?>
Quantity -
<select name="" id="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
-
<input type="hidden" value = "<?php echo $book['id']; ?>">
<input type="button" value = "Select this book ">
<?php
echo '</div>';
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input:button').click(function(){
$.post('calculate.php',
{
bookId : $(this).prev('input:hidden').val(),
quantity: $(this).prev().prev('select').val()
},
function(data)
{
$('#cart').html(data);
}
)
});
});
</script>
</body>
Try moving the $bookFound = false; statement above the if(count($booksInfo) > 0) statement. If the if(count($booksInfo) > 0){} block is not executed, $bookFound is not initialized for when you get to the if(!$bookFound){} block.

PHP Math Pythagoras

Okay, I've coded this pythagoras-solver kind of thing, and I was wondering any ways I could improve it, or make it more efficient?
<?php
$sides = array('1' => 'Hypotenuse',
'2' => 'Adjacent',
'3' => 'Opposite');
function createSideDropdown($name) {
global $sides;
$option = "<select name='".$name."'>";
if(!empty($sides)) {
foreach($sides as $id => $sideDesc) {
$option .= "<option value='".$id."'>".$sideDesc."</option>";
}
} else {
die("Error fetching sides!");
}
$option .= "</select>";
echo $option;
}
try {
if(!empty($_POST['submit'])) {
if(empty($_POST['val1']) || empty($_POST['val2'])) {
throw new Exception("Please enter an integer in both boxes.");
}
if(!is_numeric($_POST['val1']) || !is_numeric($_POST['val2'])) {
throw new Exception("One of the numbers you entered is not a valid integer.");
}
$val1 = $_POST['val1'];
$val2 = $_POST['val2'];
$val1numtype = $_POST['val1type'];
$val2numtype = $_POST['val2type'];
$val1nametype = $sides[$val1numtype];
$val2nametype = $sides[$val2numtype];
if($val1numtype == $val2numtype) {
throw new Exception("The two sides of the triangle must be different");
}
if($val1nametype == "Hypotenuse" || $val2nametype == "hypotenuse") {
// work out a small side
$bignum = max($val1, $val2);
$smallnum = min($val1, $val2);
$sqTotal = ($bignum * $bignum) - ($smallnum * $smallnum);
$total = sqrt($sqTotal);
echo $bignum."² - ".$smallnum."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
} else {
// work out the hypotenuse
$sq1 = $val1 * $val1;
$sq2 = $val2 * $val2;
$sqTotal = $sq1 + $sq2;
$total = sqrt($sqTotal);
echo $val1."² + ".$val2."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
}
echo "<br /><br />"; // Seperate the working out from the input
}
} catch(Exception $e) {
echo $e->getMessage()."<br/><br/>";
}
?>
<form method='POST' action='index.php'>
Value 1: <input type='text' name='val1' />
<?php createSideDropdown("val1type"); ?>
<br /><br />
Value 2: <input type='text' name='val2' />
<?php createSideDropdown("val2type"); ?>
<br />
<select name="mes">
<option name="mm">mm</option>
<option name="cm">cm</option>
<option name="m">m</option>
<option name="cm">km</option>
</select>
<br />
<input type="submit" name="submit" />
</form>
?>
Well, one thing you can certainly do is:
HTML on its own and PHP on its own - separate that. And then, I would continue having a look at the rest.
Also, you could do your exceptions with JavaScript - I mean, use JavaScript to parse the text fields and write the errors with JavaScript. Rather than always submitting the form. - Still you should parse the fields in PHP as well.
Then, make a class out of it and make a proper documentation of it such as
/**
* This method does bla
* #param Int a
*/
Don't use globals - could be done with class attributes.

Categories