By using PHP to handle the user input and interface, and using MySQL to store and retrieve the data and perform calculations on it. Here’s an example of how you might create a basic calculator that performs addition, subtraction, multiplication and division on two numbers:
<?php $conn = mysqli_connect("host", "username", "password", "database_name"); if(isset($_POST['calculate'])){ $num1 = $_POST['num1']; $num2 = $_POST['num2']; $operator = $_POST['operator']; switch ($operator) { case 'add': $result = $num1 + $num2; break; case 'subtract': $result = $num1 - $num2; break; case 'multiply': $result = $num1 * $num2; break; case 'divide': if($num2 == 0) { $result = "Cannot divide by zero!"; } else { $result = $num1 / $num2; } break; } $query = "INSERT INTO calculations (num1, num2, operator, result) VALUES ($num1, $num2, '$operator', $result)"; $result_query = mysqli_query($conn, $query); } ?> <form method="post" action="index.php"> <input type="text" name="num1" placeholder="Number 1"> <br> <input type="text" name="num2" placeholder="Number 2"> <br> <select name="operator"> <option value="add">Add</option> <option value="subtract">Subtract</option> <option value="multiply">Multiply</option> <option value="divide">Divide</option> </select> <br><br> <button type="submit" name="calculate">Calculate</button> </form> <?php if(isset($result)) { echo "Result: " . $result; } ?>
In this example, the PHP script first establishes a connection to the MySQL server using the mysqli_connect
function and passing in the necessary credentials.
When the form is submitted, the script retrieves the values of the input fields (num1
, num2
, and operator
) from the $_POST
superglobal.
It then uses a switch statement to evaluate the operator and perform the corresponding calculation. It also checks the second number for division operation if it’s equal to zero, if yes it will return “Cannot divide by zero!” to the user.
Finally, it constructs an SQL INSERT
statement and uses the mysqli_query
function to execute the statement and insert the calculation data into the ‘calculations’ table.
It then prints the result of the calculation and if the calculations table already exists in the database, you should make sure to have it created before running the script
Please note that this is just a basic example and you should use prepared statements and user input validation to protect against SQL injection and other security risks when working with user input and databases.