Make PHP Calculator Store and Display History
I am new to PHP and I am trying to create a simple calculator that also displays history (past calculations) in a div on the page.
The first field enters something like "4+" and "3" in the second and it displays "4 + 3 = 7" in a div called "results". However, I want to show the entire history of results there, so when I do a new calculation, the div result will be displayed in both calculations / results. What's the best way to do this in PHP? Can you choose DOMNode::appendChild
?
Here is my code:
<div id="form">
<form action="" method="post">
<input type ="text" name="firstNumber">
<input type ="text" name="secondNumber">
<input type ="submit" style="display:none">
</form>
</div>
Result:
<?php
$number1 = $_POST["firstNumber"];
$number2 = (int)$_POST["secondNumber"];
@$operator = substr($number1, -1);
switch($operator){
case '+':
$result = (int)$number1+$number2;
echo $result;
break;
case '-':
$result = (int)$number1-$number2;
echo $result;
break;
case '*':
$result = (int)$number1*$number2;
echo $result;
break;
case '/':
$result = (int)$number1/$number2;
echo $result;
break;
}
?>
<div id="results">
<?php echo substr($number1,0, -1);
echo $operator;
echo $number2; ?>
<br>=
<?php echo $result; ?>
</div>
Thanks for helping!
source to share
To keep the server-side history you need a database like MySQL, a caching server like Memcache or Redis, or you can just save the results to $_SESSION
. Here is a good resource on how to store data in a session. If you save it in $_SESSION
, your history will be lost when the user clears their cookies (or logs out if you implement user accounts).
source to share