View Full Version : PHP form calculator scripts - help

01-26-2007, 03:53 PM
I would really like to develop the skills to be able to do bespoke PHP formulas and calculations within the page - similar to some of the savings calculators examples below:
I am proficient at HTML and CSS and have set up PHP applications (though never really got involved with the code), but would really learn more PHP skills and I have usually found that the best way to learn things is to set a challenge - and PHP in page form calcuations would be really useful.
I have found a couple of tutorials about developing actual PHP calculators (i.e. not what i want) but am not sure I am any closer to figuring this out. Would really appreciate it if somebody could point me in the right direction to get started ...

01-26-2007, 04:06 PM
What's cool about these type of calculations in PHP is that you can make them as easy or as complicated as you want. A simple multiplying calculator could be done simply with code like this:

First, start a form and two text input boxes.

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">

<input type="text" name="1st_number" value="" /> x <input type="text" name="2nd_number" value="" /> = <?=$number?><br />

<input type="submit" name="multiply" value="Calculate" />


As you can see, the action that the form is pointing to is itself, so we need to write PHP code on the same page. We'll write code to look and see if the "Calculate" button has been clicked or not and then calculate the number. Also, notice that <?= is used instead of using an echo(). They mean the same thing. <?= is just a much faster, cleaner way to quickly echo a variable. Ok, so here's the PHP code to calculate the $number:


// If the submit button has been clicked

if (isset($_POST['multiply'])) {

// Put the POSTed numbers into variables so we can easily work with them
$1st_number = $_POST['1st_number'];
$2nd_number = $_POST['2nd_number'];

$number = $1st_number * $2nd_number;

And that will make the $number variable have the result of the first number times the second number.

So that's just a really simple, silly example. But as you can see, you can do wayyyy more complicated and helpful calculations than that. I'm currently working on a budget script that will take how much you plan to spend in a certain budget category and then subtract how much you've actually spent in that category each month, and it will echo your balance. Fun stuff!

01-27-2007, 12:59 AM
Cheers JohnDubya - sounds like you are having fun there :-)

Really useful start - much appreciated.