Populating Input Fields with PHP Variables
You want to pre-fill a form field with a calculated value instead of displaying the result directly in the response body. This is a common requirement when building wizards, multi-step forms, or dashboards where state needs to be preserved across requests without triggering a full page reload. The core concept here is the HTML value attribute: by setting this attribute on an <input> element, you instruct the browser to render that specific text inside the field when the page loads.
To achieve this in your current setup, you need to separate the logic that performs the calculation from the logic that renders the form. Your existing script currently echoes the result immediately using echo, which terminates the response before the HTML form is sent back to the client. To populate the input, you must output valid HTML where the <input name="result"> tag includes a value attribute containing the calculated number.
Here is how you modify the PHP logic. First, ensure the calculation happens only after validating the inputs. Then, assign the result to a variable and pass it directly into the HTML string.
if(isset($_POST['submit'])){
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$sign = $_POST['sign'];
// Basic validation remains necessary
if($value1 === '' || $value2 === '') {
echo "<script>alert('Please Enter Both Values')</script>";
exit();
}
// Perform calculation
$result = null;
if($sign == '+') {
$result = (float)$value1 + (float)$value2;
} elseif($sign == '-') {
$result = (float)$value1 - (float)$value2;
} elseif($sign == '*') {
$result = (float)$value1 * (float)$value2;
} elseif($sign == '/') {
if($value2 == 0) {
echo "<script>alert('Cannot divide by zero')</script>";
exit();
}
$result = (float)$value1 / (float)$value2;
}
// Only proceed to render if a valid result exists
if($result !== null) {
?>
<html>
<head>
<title>PHP Calculator</title>
<style>
body { font-family: sans-serif; padding: 20px; }
input[type="text"] { width: 100%; max-width: 300px; margin-bottom: 10px; }
</style>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<form method="post" action="">
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>
<!-- The key change: setting the value attribute -->
Result:<br><input type="text" name="result" value="<?php echo htmlspecialchars($result); ?>">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
exit();
}
}
?>
Handling State Without Redirects
In the original code, you posted to phptest.php, and the script echoed text. If you want the result to appear inside the input box on a subsequent load (for example, if the user submits and then clicks "Submit" again), the form action needs to point back to the same script. The code above uses action="" which defaults to the current file.
A critical detail in the implementation above is the use of htmlspecialchars(). When you insert a variable into an HTML attribute, raw data can introduce breaking characters like quotes or angle brackets if the user inputs malicious strings (e.g., ' onclick="alert('xss')"). Even though this is a calculator, sanitizing output attributes is a fundamental security practice to prevent Cross-Site Scripting (XSS).
The Trade-Off: Echo vs. Return
You might wonder why we didn't just echo the result and let the browser handle it. In web development, there are two distinct modes for handling data:
- Response Mode: Calculating a value and returning it as part of the HTTP response (what your original code did).
- Stateful Mode: Returning a form where the state is preserved in the DOM (what you requested).
By setting the value attribute, you are effectively telling the browser, "Remember this answer for now." This allows the user to correct their input or change the operator and have the previous calculation persist as a suggestion. However, be aware that if the user modifies the fields and submits again with a new operation, the form will reload and recalculate based on the new inputs. The value attribute simply reflects the current state of the application logic at the moment of rendering.
If you are moving to a larger framework like Laravel, this pattern becomes even more standard. You would typically calculate the result in your controller, pass it to the view, and let the template engine handle the rendering of the input field with the passed variable. For instance, using a Blade template:
<div>
<input type="text" name="result" value="{{ old('result', $result) }}">
</div>
This approach scales better because it separates business logic from presentation logic, making your code easier to maintain as the application grows.
