Interactive Quadratic Solver Form

This example demonstrates how to create an interactive quadratic formula calculator with form handling using PHP.

quadratic.php
    
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quadratic Solver</title>
    <link href="lab.css" rel="stylesheet">
    <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=default'>
</script>
</head>
    
<body>

<h2>Quadratic Formula </h2>

\( x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \)

<h3>Enter values for a, b, and c:</h3>

  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    a: <input type="number" step="any" name="a" required 
        value="<?php if (isset($_POST['a'])) echo htmlspecialchars($_POST['a']); ?>"><br><br>
    b: <input type="number" step="any" name="b" required 
        value="<?php if (isset($_POST['b'])) echo htmlspecialchars($_POST['b']); ?>"><br><br>
    c: <input type="number" step="any" name="c" required 
        value="<?php if (isset($_POST['c'])) echo htmlspecialchars($_POST['c']); ?>"><br><br>
    <input type="submit" value="Solve">
  </form>

  <h3>Result:</h3>

    <?php

    function solveQuadratic($a, $b, $c) {

          if ($a == 0) {
              return "This is not a quadratic equation (a cannot be 0).";
          }
          
          $discriminant = ($b * $b) - (4 * $a * $c);
      
          if ($discriminant < 0) {
              return "No real solutions.";
          } elseif ($discriminant == 0) {
              $x = -$b / (2 * $a);
              return "One real solution: x = $x";
          } else {
              $sqrtDisc = sqrt($discriminant);
              $x1 = (-$b + $sqrtDisc) / (2 * $a);
              $x2 = (-$b - $sqrtDisc) / (2 * $a);
              return "Two real solutions: x₁ = $x1 and x₂ = $x2";
          }
      }

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $a = (float) $_POST["a"];
        $b = (float) $_POST["b"];
        $c = (float) $_POST["c"];

        echo solveQuadratic($a,$b,$c);
    }

  ?>

</body>
</html>