March 25, 2012

How to write a PHP code on simple math expression?

Question by user1290968

I am a newbie of PHP coding, and want to do a simple math example, d=(a+b)/c.

The values of a and b will be submitted by the user from a webpage containing PHP form.
The value of c is predefined in the PHP page.

When the user click “submit” in this webpage.
I expect to get the result of d in the bottom of the same webpage.

Any example code will be greatly appreciated.

Answer by ocanal

<form method="POST" action="">
<input type="hidden" id="c" name="c" value="10" />
<label for="a">a: </label>
<input type="text" id="a" name="a" /> <br />
<label for="b">b: </label>
<input type="text" id="b" name="b" />
<input type="submit" />
</form>
<br />

<?php
if (isset($_POST["a"]) && isset($_POST["b"]) && isset($_POST["c"])) {
    if (is_numeric($_POST["a"]) && is_numeric($_POST["b"]) && is_numeric($_POST["c"])) {
        $d = ($_POST["a"] + $_POST["b"])/$_POST["c"];
        echo "d = ". $d;
    } else {
        echo "all values must be numeric!"
    }
}
?>

Answer by Starx

It is not that different from other languages. Assuming you are using POST to submit the form.

$d = ($_POST['a'] + $_POST['b'])/$c;

WARNING: Injection Vulnerability if used in SQL query. But shouldn’t be a problem while learning.

To display the result. Use echo statement, which prints out the text/variable to the browser.

<?PHP echo $d; ?>

Place this snippet, where you want to display.

For example:

<div> Here is the result: <?PHP echo $d; ?> </div>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!