sam sam - 6 months ago 16
PHP Question

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 its simple but I am new in PHP.

Answer

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:'';?>">