newbie here...
Im trying to create a simple php quote calculator, I've got a quantity field and 2 lest menus.
What I'm trying to do is multiply the quantity by a assigned value of the one list item added to quantity multiplied by an assigned value of the other list item, no combination of the two list items will be the same.
I've got this to work fine except once one of the list items is the same the calculation is thrown off...
if( isset( $_REQUEST['calculate'] ))
{
$type=$_REQUEST['type'] && $lam=$_REQUEST['lam'];
if($type=="One Side Colour" && $lam=="None")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*.70+$add1*0;
}
if($type=="One Side Colour" && $lam=="One Side")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*.70+$add1*.15;
}
if($type=="Two Sides Colour" && $lam=="None")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*1.4+$add1*0;
}
the last "if" confuses the calculation
Any ideas to get around this?
Some code fix ups:
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity']; // Casts the value to Integer
if($type=="One Side Colour" && $lam=="None"){
$res = ($add1 * .70) + ($add1 * 0); // Unclear 0 * anything = 0
}
if($type=="One Side Colour" && $lam=="One Side"){
$res = ($add1 * .70) + ($add1 * .15);
}
if($type=="Two Sides Colour" && $lam=="None"){
$res = ($add1 * 1.4) + ($add1 * 0); // Another 0 issue?
}
}
Added a few ( ) to outline the order or operations. Also don't get why you multiply by 0...
Edit
After some of your comments, this would be condensed some:
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity'];
if($type == "One Side Colour") {
$res = ($add1 * .70) + ($add1 * ($lam == "One Side" ? .15 : 0));
} elseif($type == "Two Sides Colour") {
$res = ($add1 * 1.4);
}
}
Edit 2
Looked at your HTML and have a few suggestions:
<table width="450" cellpadding="5" border="0" align="center">
<tbody><tr>
<td>Quantity</td>
<td>
<input type="text" size="5" name="quantity" value="<?php echo (isset($_REQUEST['quantity'])?$_REQUEST['quantity']:''); ?>"> Business Cards</td>
</tr>
<tr>
<td>Number of Sides</td>
<td>
<select name="type">
<?php
$type = array(
"One Side Colour",
"Two Sides Colour",
"One Side Black/White",
"One Side Colour/Other Side Black/White"
);
foreach($type as $o){
if(isset($_REQUEST['type']) && $_REQUEST['type'] == $o){
echo " <option selected='selected'>$o</option\r\n";
} else {
echo " <option>$o</option>\r\n";
}
}
?>
</select></td>
</tr>
<tr>
<td>Lamination</td>
<td>
<select name="lam">
<?php
$lam = array(
"None",
"One Side",
"Both Sides"
);
foreach($lam as $l){
if(isset($_REQUEST['lam']) && $_REQUEST['lam'] == $l){
echo " <option selected='selected'>$l</option\r\n";
} else {
echo " <option>$l</option>\r\n";
}
?>
</select></td>
</tr>
<tr>
<td> </td>
<td><input type="Submit" value="calculate" name="calculate"></td>
</tr>
<tr><td>Price</td>
<td style="font-weight:bolder;font-size: 20px;"><?php echo (isset($res)?"P$res":""); ?></td>
</tr>
<tr>
</tr></tbody></table>
This will allow your form to retain the selections each time the price is calculated.
Hope this will help you...
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity'];
if($type == "One Side Colour") {
$res = ($add1 * .70) + ($add1 * ($lam == "One Side" ? .15 : 0));
} elseif($type == "Two Sides Colour") {
$res = ($add1 * 1.4);
}}
Also, I've created a calculator, regarding auto transport quote
If you need any help and code of that calculator than contact me.
Related
I am creating an online grocery site where a user can enter his/her full name & address and then proceed to purchase groceries.
There are 20 grocery items to choose from - if the user wants an item, they can simply enter how many units of that item they want; this is the html code for for just 1 of the 20 items.
<tr>
<td> Milk - $3.99/carton </td>
<td> <input type="number" name="amtMilk" min=0> </td>
</tr>
At the bottom of the page there is a submit button which leads to a confirmation page in php. The confirmation page outputs the users name, address, all the items ordered and a total before and after tax.
I have written out the PHP for this however, it doesn't seem to be working correctly. Below is my code shortened to 4 items:
<?php
<h2> Customer Details: </h2>
<p>Customer Name: </p> echo $_POST['Name'];
<p>Address: </p> echo $_POST['Address'];
$total = 0;
<p>You ordered: </p>
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
foreach($POSTvalues as $key) {
if ($_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
elseif ($_POST['amtEggs'] > 0 ) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
elseif ($_POST['amtBread'] > 0 ) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
elseif ($_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total"; <br>
$afterTax = $total*0.13 + $total
$afterDelivery = $afterTax + 3.50
echo "Your total after tax is: $afterTax"; <br>
echo "Your total after delivery is: $afterDelivery";<br>
<h3> GRAND TOTAL: </h3> echo "$afterDelivery";
?>
Can anyone point out what i'm doing wrong or how I can fix this so get the desired output?
There is no need for the foreach loop, and thus no need for the $POSTvalues array.
Use independent if statements without the elseif.
A little psuedocode...
if (value1 > 0 )
{
add to total
print item
}
if (value2 > 0 )
{
add to total
print item
}
if (value3 > 0 )
{
add to total
print item
}
if (value4 > 0 )
{
add to total
print item
}
Fun fact: PHP turns elements with names structured like arrays into PHP arrays.
So, you can do this:
<?php
$array = array(
"milk" => array(
"price" => 3.99,
"unit" => "carton",
),
"eggs" => array(
"price" => 2.99,
"unit" => "dozen",
),
);
if (isset($_POST['amt'])) {
var_dump($_POST['amt']);
$total = 0;
foreach ($_POST['amt'] as $name=>$num) {
if($num > 0) {
$price = $array[$name]['price'];
$amt = $_POST['amt'];
$total += $price * $num;
echo $num . " " . ucfirst($name) . ", ";
}
}
echo "<br />Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo '<form method="POST"><button type="submit">Back</button></form>';
} else {
?><form method="POST"><table><?php
foreach ($array as $name=>$item) {
?>
<tr>
<td> <?php echo ucfirst($name); ?> - $<?php echo $item['price']; ?>/<?php echo $item['unit']; ?> </td>
<td> <input type="number" name="amt[<?php echo $name; ?>]" min=0> </td>
</tr><?php
}
?></table><input type="submit"></form><?php
}
I would consider either passing your price as a hidden field (for example, with the name price[milk]), or ensuring your array is available after you've submitted the form like I have done above. That way you don't have to hard-code in prices. The way you have it, it's going to be a nightmare to change if the prices change!
To add a new item, all you need to do is add a new key/array pair to the $array. No additional coding on the back-end. Just results.
Check it out here.
you're doing many things wrong.
so, how are you trying to display html inside php without using print/echo?
So here's revised code, hope this will resolve your issues.
<?php
echo '<h2> Customer Details: </h2>';
echo '<p>Customer Name: </p>'. $_POST['Name'];
echo '<p>Address: </p>'. $_POST['Address'];
$total = 0;
echo '<p>You ordered: </p>';
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
//foreach($POSTvalues as $key)
{
if (isset($_POST['amtMilk']) && $_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
if (isset($_POST['amtEggs']) && $_POST['amtEggs'] > 0) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
if (isset($_POST['amtBread']) && $_POST['amtBread'] > 0) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
if (isset($_POST['amtCereal']) && $_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo "<h3> GRAND TOTAL: </h3>$afterDelivery";
?>
EDIT
Comment out the foreach($POSTvalues as $key) and change all elseif to if.
add another condition in if statement like this && $_POST['amtCereal'] > 0 to ensure that it has value greater than 0
I have the following PHP script that takes the selected $empfullname from the user and prints 'timecard_html' based on the selection. I am trying to make it capable that if they select 'All' then the script prints out all of the employees in the list each in a separate timecard_html. Here is the php script:
if ($empfullname == 'All') {
$query = "select empfullname from ".$db_prefix."employees";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)) {
$empfullname = ("".$row['empfullname']."");
print timecard_html($empfullname, $local_timestamp_in_week);
unset($empfullname);
}
} else {
print timecard_html($empfullname, $local_timestamp_in_week);
}
Also, here is timecard_html in case you need to see it:
function timecard_html($empfullname, $local_timestamp_in_week) {
// Return html of employee's timecard.
global $show_display_name, $one_week;
// SQL search parameters for one work week.
$begin_local_timestamp = work_week_begin($local_timestamp_in_week);
$end_local_timestamp = $begin_local_timestamp + $one_week;
// Define helper functions for printing timecard header, footer, and for printing every row.
function print_header($tc) {
// Print timecard html header.
global $overtime_week_limit, $timecard_display_running_total;
$overtime_col = $overtime_week_limit > 0 ? "\n <th align=\"center\" class=\"ovt\" title=\"Overtime hours\">OT</th>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <th align=\"center\" class=\"total\" title=\"Running total of regular work hours and overtime to date.\">Total</th>" : '';
print <<<End_Of_HTML
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<thead>
<tr>
<th align="left">In/Out</th>
<th align="center">Time</th>
<th align="center">Date</th>
<th align="center" class="hrs" title="Regular work hours.">Hrs</th>$overtime_col$total_col
<th align="left" class="notes">Notes</th>
</tr>
</thead>
<tbody>
End_Of_HTML;
}
function print_row($tc) {
// Configuration variables.
global $timefmt, $datefmt;
global $overtime_week_limit, $timecard_list_punch_outs, $timecard_display_hours_minutes;
global $timecard_hours_include_overtime, $timecard_display_running_total;
static $print_count = 0;
if (($tc->in_or_out == 1) || $timecard_list_punch_outs == 'yes') {
$h_color = htmlentities($tc->row['color']);
$h_inout = htmlentities($tc->row['inout']);
$h_time = date($timefmt, $tc->start_time);
$h_date = date($datefmt, $tc->start_time);
if ($timecard_display_hours_minutes == "yes") {
$h_hours = hrs_min((($timecard_hours_include_overtime == "yes") ? ($tc->hours + $tc->overtime) : $tc->hours));
$h_overtime = hrs_min($tc->overtime);
$h_total = hrs_min(($tc->week_hours + $tc->overtime_hours));
}
else {
$h_hours = sprintf("%01.02f",(($timecard_hours_include_overtime == "yes") ? ($tc->hours + $tc->overtime) : $tc->hours));
$h_overtime = sprintf("%01.02f",$tc->overtime);
$h_total = sprintf("%01.02f",($tc->week_hours + $tc->overtime_hours));
}
$h_notes = htmlentities($tc->row['notes']);
if ($tc->in_or_out != 1) {
// Don't display hours on "out" records.
$h_hours = $h_overtime = $h_total = '';
}
$row_class = (++$print_count % 2) ? 'odd' : 'even';
$overtime_col = $overtime_week_limit > 0 ? "\n <td align=\"right\" class=\"ovt\">$h_overtime</td>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <td align=\"right\" class=\"total\">$h_total</td>" : '';
print <<<End_Of_HTML
<tr class="display_row $row_class">
<td align="left" class="job_code" style="color:$h_color">$h_inout</td>
<td align="right">$h_time</td>
<td align="right">$h_date</td>
<td align="right" class="hrs">$h_hours</td>$overtime_col$total_col
<td align="left" class="notes">$h_notes</td>
</tr>
End_Of_HTML;
}
}
function print_footer($tc) {
global $timecard_display_running_total, $timecard_hours_include_overtime;
global $timecard_display_hours_minutes, $overtime_week_limit;
// Set flag to print paragraph of totals if they're not already obvious.
$print_totals = ($timecard_display_running_total == "yes" || $timecard_hours_include_overtime != "yes") ? true : false;
$h_total_hours = sprintf("%01.02f",($tc->week_hours+$tc->overtime_hours));
$h_totals = ($print_totals) ? "\n<p>Total for week: ".hrs_min($tc->week_hours + $tc->overtime_hours)." ($h_total_hours hours)</p>" : '';
$h_ovt_total_hours = sprintf("%01.02f",$tc->overtime_hours);
$h_overtime_totals = ($print_totals && $tc->overtime_hours > 0) ? "\n<p>Total overtime: ".hrs_min($tc->overtime_hours)." ($h_ovt_total_hours hours)</p>" : '';
$h_day_total_hours = sprintf("%01.02f",$tc->today_hours);
$h_today_hours = ($tc->today_hours !== null) ? "<p>Total today: ".hrs_min($tc->today_hours)." ($h_day_total_hours hours)</p>" : '';
if ($timecard_display_running_total != "yes") {
// Print row of totals
$total_hours = $timecard_hours_include_overtime == "yes" ? ($tc->week_hours+$tc->overtime_hours) : $tc->week_hours;
$h_hours = $timecard_display_hours_minutes == "yes" ? hrs_min($total_hours) : $h_total_hours;
$overtime_col = $overtime_week_limit > 0 ? "\n <td align=\"right\" class=\"ovt\">".($timecard_display_hours_minutes == "yes" ? hrs_min($tc->overtime_hours) : $h_ovt_total_hours)."</td>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <td align=\"right\" class=\"total\">".($timecard_display_hours_minutes == "yes" ? hrs_min($tc->week_hours+$tc->overtime_hours) : $h_total_hours)."</td>" : '';
print <<<End_Of_HTML
<tr class="total_row">
<td align="left"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right" class="hrs">$h_hours</td>$overtime_col$total_col
<td align="left" class="notes"></td>
</tr>
End_Of_HTML;
}
print <<<End_Of_HTML
</tbody>
</table>
End_Of_HTML;
if ($timecard_display_running_total == "yes" || $timecard_hours_include_overtime != "yes" || $h_today_hours) {
// Add totals text if totals are not already displayed or if summing the hours column is confusing.
print <<<End_Of_HTML
<div class="totals">
$h_today_hours$h_totals$h_overtime_totals
</div>
End_Of_HTML;
}
}
// End of helper function definitions.
// Print timecard page header.
$h_name_header = htmlentities( ($show_display_name == 'yes' ? get_employee_name($empfullname) : $empfullname) );
$begin_date = date('l F j, Y',$begin_local_timestamp);
print <<<End_Of_HTML
<div id="punchclock" class="timecard">
<h2>Timecard</h2>
<h3>$h_name_header</h3>
<h4>Week beginning $begin_date</h4>
End_Of_HTML;
// Print timecard.
$tc = new Timecard($empfullname,$begin_local_timestamp, $end_local_timestamp);
list($row_count, $total_hours, $overtime_hours, $today_hours) = $tc->walk(print_header, print_row, print_footer);
if ($row_count <= 0) print error_msg("No records were found.");
// Print timecard page footer.
print <<<End_Of_HTML
</div> <!-- timecard -->
End_Of_HTML;
}
?>
As of right now if 'All' is selected it prints the results for the first employee in the table, but not any of the other ones. Also, if I just print ("".$row['empfullname']."") it prints out all the employees. Do I maybe need to use a for each loop instead of a while loop?
Thanks in advance.
Your problem is that your are defining functions in your function. That will work the first time when you call your function, but the second time it will cause a fatal error as the function is already defined.
See a simple example here.
Moving the inner function declarations out of the main function should solve this specific problem.
You should also always enable error handling and displaying while developing. In this case you would have caught the problem inmediately.
Just put this at the top of the main script:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);
In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.
I'm new to programming language. I want to know can i get value from other field and pass to other field in same form without using javascript ? Can someone explain to me ? Thank u.
This my form page
<form id="leave_form">
<table><tr>
<td width="70"><b>*</b> Date From:</td>
<td width="120"><span id="lv_date_from_btn"><input readonly class="field_required control" onchange="validateLeave('from')" id="lv_date_from" name="date_from" value="<?php echo $start_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<tr>
<td width="70"><b>*</b> Date To:</td>
<td width="120"><span id="lv_date_to_btn"><input readonly class="field_required control" onchange="validateLeave('to')" id="lv_date_to" name="date_to" value="<?php echo $end_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<?php if ($userid == '609'):?>
<tr>
<td><b>*</b> Relief Staff: </td>
<td>
<select name="userid" id="frm_userid2" class="field_required control" onchange="validateLeave('relief')" >
<?php
$leavefrom = $_REQUEST['from'];
$leaveto = $_REQUEST['to'];
if (empty($leavefrom))
{
echo '<option value="" selected disabled>Select...</option>';
}
else{
echo '<option value="" selected disabled>Select...</option>';
$sql = "
SELECT distinct fullname FROM core_user LEFT JOIN lms_tran ON lms_tran.userid = core_user.userid where core_user.userid NOT IN (SELECT userid FROM lms_tran WHERE date_from BETWEEN '$leavefrom' AND '$leaveto' AND app_status = 'Approved') AND core_user.userid != 609 AND core_user.status = 'Y' ORDER by fullname ASC
";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row["userid"].'">'.$row["fullname"].'</option>';
}
}?>
</select>
</td>
</tr>
<?php endif; ?>
</table>
</form>
and this is javascript
function validateLeave(type)
{
var days= jQuery('#frm_days').val();
var from = jQuery('#lv_date_from').val();
var to = jQuery('#lv_date_to').val();
var relief = jQuery('#frm_userid2').val();
if (type != 'check')
{
days_incorrect = true;
}
if (type == 'days' || type == 'from')
{
to = '';
relief = '';
}
if (type == 'to')
{
days = '';
}
if (
(
(days == '' ? 0 : 1) +
(to == '' ? 0 : 1) +
(from == '' ? 0 : 1)
) < 2
)
{
days_correct = false;
return;
}
days = parseFloat(days);
jQuery('#frm_days').val(days);
jQuery('.control').attr('disabled', true);
jQuery('#lv_loading').show();
jQuery.post('index.php?_m=lms&_a=leave_validate&from='+from+'&to='+to, {from:from,to:to,days:days}, function(res){
eval('var r = '+res+';');
if (r.status == 'OK')
{
days_incorrect = false;
if (r.to)
{
jQuery('#lv_date_to').val(r.to);
}
if (r.from)
{
jQuery('#lv_date_from').val(r.from);
}
if (r.days)
{
jQuery('#frm_days').val(r.days);
}
}
else if (r.status == 'HOLIDAYERROR')
{
alert('Incorrect leave start date. Leave start date can not fall into Weekend or Public Holidays');
days_incorrect = true;
}
else
{
alert('Incorrect leave period. Please check back Leave Start, Leave End and Leave Days')
days_incorrect = true;
}
jQuery('.control').attr('disabled', false);
jQuery('#lv_loading').hide();
});
}
and i could'nt get the value return in php code as i hv pass value via jQuery.
No, you can't. The only way to do something interactive is to do it with javascript if you the to see it. If it doesn't matter you can do this on the server by assigning the second variable with the value of the first.
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.