Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set value of input field by php variable's value

I have a simple php calculator which code is:

<html>
    <head>
        <title>PHP calculator</title>
    </head>

    <body bgcolor="orange">
        <h1 align="center">This is PHP Calculator</h1>
        <center>
            <form method="post" action="phptest.php">
                Type Value 1:<br><input type="text" name="value1"><br>
                Type value 2:<br><input type="text" name="value2"><br>
                Operator:<br><input type="text" name="sign"><br>
                Result:<br><input type"text" name="result">
                <div align="center">
                    <input type="submit" name="submit" value="Submit">
                </div>
            </form>
        </center>

<?php
    if(isset($_POST['submit'])){
        $value1=$_POST['value1'];
        $value2=$_POST['value2'];
        $sign=$_POST['sign'];

        if($value1=='') {
            echo "<script>alert('Please Enter Value 1')</script>";
            exit();
        }

        if($value2=='') {
            echo "<script>alert('Please Enter Value 2')</script>";
            exit();
        }

        if($sign=='+') {
            echo "Your answer is: " , $value1+$value2;
            exit();
        }

        if($sign=='-') {
            echo "Your answer is: " , $value1-$value2;
            exit();
        }

        if($sign=='*') {
            echo "Your answer is: " , $value1*$value2;
            exit();
        }

        if($sign=='/') {
            echo "Your answer is: " , $value1/$value2;
            exit();
        }
    }
?>

All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.

like image 417
sam Avatar asked Mar 18 '14 15:03

sam


1 Answers

One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -

<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
    $value1=$_POST['value1'];
    $value2=$_POST['value2'];
    $sign=$_POST['sign'];
    ...
        //Adding to $result variable
    if($sign=='-') {
      $result = $value1-$value2;
    }
    //Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
like image 110
Kamehameha Avatar answered Sep 20 '22 01:09

Kamehameha