Create a Calculator using PHP and MySQL

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:

$conn = mysqli_connect("host", "username", "password", "database_name");

  $num1 = $_POST['num1'];
  $num2 = $_POST['num2'];
  $operator = $_POST['operator'];

  switch ($operator) {
    case 'add':
        $result = $num1 + $num2;
    case 'subtract':
        $result = $num1 - $num2;
    case 'multiply':
        $result = $num1 * $num2;
    case 'divide':
        if($num2 == 0) {
            $result = "Cannot divide by zero!";
        } else {
            $result = $num1 / $num2;
  $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">
  <input type="text" name="num2" placeholder="Number 2">
  <select name="operator">
    <option value="add">Add</option>
    <option value="subtract">Subtract</option>
    <option value="multiply">Multiply</option>
    <option value="divide">Divide</option>
  <button type="submit" name="calculate">Calculate</button>

  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.