Forum Moderators: coopster
I am very new to PHP, and I am wondering if anyone can point me towards an example of how to use a PHP form to have the user input some values, perform a mathematical operation, and then write out the answer on the same screen?
For example, the form would have 2 input fields, assigned to variable_a and variable_b respectively. I would like the user to input the integers, click a "calc" button, and have the script print out something to the effect of "the answer is" and then the sum of the values.
I am working this up towards a more complex mathematical equation, which I am sure I could get working if I could find a simple example of this somewhere.
Any help is appreciated!
$variable_a = 4;
$variable_b = 2;
$answer = $variable_a + $variable_b;
(answer = 6)
$answer = $variable_a / $variable_b;
(answer = 2)
$answer = $variable_a * $variable_b;
(answer = 8)
$answer = $variable_a - $variable_b;
(answer = 2)
Let me know if you need a "full" example.
<?
if($_POST['Submit']!=''){
$variable_a = $_POST['variable_a'];
$variable_b = $_POST['variable_b'];$result = $variable_a + $variable_b;
echo "<h1>$variable_a + $variable_b = $result</h1>";
}
?><form name="calc" method="post">
<input name="variable_a" type="text" id="variable_a">
+
<input name="variable_b" type="text" id="variable_b">
<input type="submit" name="Submit" value="Calc">
</form>
<?php phpinfo()?>
All I did with the code Niels posted above is cut/paste it into a blank file called calc.php, uploaded it to my server, and viewed it through a browser. Is that what I was supposed to do?
Other than having PHP installed, you need to run it through your web server so it will execute. You will use a path like 127.0.0.1/test.php. If you are just doubleclicking on the file and runing it that way it likely won't work.
Look in the address bar. Is it a web address or something like "C:\Program Files\...math.php".