calculations from user input

hi - I need to do the following:

  1. input value x a fixed value = value1
  2. input value x a fixed value = value2
  3. add the 2 items and output total.

have searched under php and java scripts, but my searches all deliver full calculator scripts.

can you point me in the right direction ?

What have you tried? It is variable assignment, followed by math operations.

Make a form that submits to itself.

if ($_POST) {
echo $_POST[‘field1’] + $_POST[‘field2’];

}

you can do something like this

[php]

input value1:
input value2:

<?php $x=""; $y=""; if(isset($_GET['x'])) { $x=$_GET['x']; } if(isset($_GET['y'])) { $y=$_GET['y']; } $result=$x+$y; echo 'result is: '.$result; ?> [/php]

you can change the $_GET ⇒ $_POST if you don’t want the data to be shown in the address bar.

make sure you understand the code if it’s your assignment :wink:

thanks Hanchan - you didn’t include my multiplication need, but even my limited knowledge was enough to work out how to add 2 more values and multiply with input x and y .

see here what I made of it:

Enter your embroidery's approx. square inch size:
Enter number of (small ) letters in your embroidery:

<?php $x=""; $y=""; $a=""; $b=""; if(isset($_GET['x'])) { $x=$_GET['x']; } if(isset($_GET['y'])) { $y=$_GET['y']; } $a=$x*1200; $b=$y*125; $result=$a+$b; echo 'Your stitch estimate is: '.$result; ?>

thanks !!

Yikes! A less than optimum example got you with a big mess in the end. Your code could be reduced by at least 50% if it was optimized. I am on a phone so I am not able to type code so well. Hopefully Ernie or Strider will show you how that can be rewritten.

One issue is with the empty variables and using isset. When you submit the form those variables are going to be set whether there is anything entered in them or not so the empty variables will never do anything. It’s just extra code sitting there. What you need to check is if they are empty or not.

I won’t get into the get versus post debate. But there are several important differences that you should know about. I suggest you do a little research to know the difference.

Hi Kevin,

the empty variable $x=""; and $y=""; is just for avoiding warning or errors to display on the page,
for example if I would not put empty variable there will be something like

Notice: Undefined variable: name in blah blah blah…

this is the simplest setting other than editing settings at php.ini to not display notices.

but this is the only way I know as a beginner, please advice us if there are better ways to optimize the code
without displaying notice or warning on the page, or the practical way of coding.

thanks in advance! :slight_smile:

Aren’t you the same guy I just wrote the stitch estimator for a week or so ago?

no :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service