Tuesday, April 22, 2025

PHP Calculator

You are advised to check corresponding YouTube video at the end of this article.

form.html


<form action="grabthings.php" method="post">
<label>First Number:</label>
<input type="text" name=first>
<br><br>

<label>Second Number:</label>
<input type="text" name=second>
<br><br>

<label>Operation:</label>
<input type="text" name=operation>
<br><br>

<input type="submit" value="Submit">
</form>

This HTML form allows users to input two numbers and an operation symbol to be performed on those numbers.

grabthings.php


<?php 

$first = $_POST["first"];
$second = $_POST["second"];
$operation = $_POST["operation"];

if ($operation == "+") {
	echo "Addition: " . ($first + $second);	
}
else if ($operation == "-") {
	echo "Substraction: " . ($first - $second);	
}
else if ($operation == "*") {
	echo "Multiplication: " . ($first * $second);	
}
else if ($operation == "/") {
	echo "Division: " . ($first / $second);	
}
else {
	echo "Weird Operation :)"	;
}
 
?>

This script takes input values from a form, consisting of two numbers and an operation (addition, subtraction, multiplication or division) to be performed on those numbers.

It uses an if-else-if block to check which operation was selected, performs the corresponding arithmetic operation on the two numbers, and outputs the result with a label indicating which operation was performed.

If the selected operation is none of the above, it outputs a message indicating that the operation is "weird".

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...