Simple calc – php example code

image_pdfimage_print

Example of using form input for two numbers and selection of one of nine possible arithmetic operation or function.

Our php application frontend is on next picture:

Our code is located in one index.php file and consist from:

  • HTML part with input form – obtain data from user, contain submit button and last part show result in two posiblle way. If there is no error message and result ist generated, then well formatted number (2 decimal numbers) is shown. Else (if number was not calculated and result is not prepared or error output message was set) warning text of red color take output (formating is created with alert message of bootstrap linked style).
  • PHP code – obtain numbers from submitted post form, controll if data available with filter_has_var(); prevent for injecting sql with simple htmlspecialchars($_POST[‚nr1‘]); and calculate result along submitted $operator = htmlspecialchars($_POST[‚operation‘]); . As demonstration for controll of user inputed data dividing by zero check take place.

Form code part of index.php follow.

<form method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
          <div class=“form-group“>
              <label>First number – n1:</label>
              <input type=“text“ name=“nr1″ class=“form-control“ value=“<?
                    php echo isset($_POST[‚nr1‘]) ? $nr1 : ‚0‘; ?>“>
          </div>
          <div class=“form-group“>
            <label>Second number – n2:</label>
            <input type=“text“ name=“nr2″ class=“form-control“ value=“<?
            php echo isset($_POST[‚nr2‘]) ? $nr2 : ‚0‘; ?>“>
          </div>
          
          <div class=“form-group“>
              <label>Select your operation:</label> <br>
              <table class=“table table-secondary „>
                <tr>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“+“ name=“operatio
                      n“ value=“+“  checked> 
                    <label> <h4> n1 + n2 </h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“-
                     “ name=“operation“ value=“-“  <?php echo ($operator == „-„) ?
                       „checked“ : “; ?> >  
                    <label><h4> n1 – n2</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“Power“ 
                     name=“operation“ value=“Power“  <?php echo ($operator ==
                     „Power“) ? „checked“ : “; ?> > 
                    <label><h4> Power n1 on n2 </h4></label> 
                    </td>
               </tr>
                <tr>        
                    <td>
                    
                    <input class=“inputSelector“ type=“radio“ id=“*“ 
                   name=“operation“ value=“*“  <?php echo ($operator == „*“) ?
                   „checked“ : “; ?>  >  
                    <label><h4> n1 * n2</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“/“ name=“operation
                     “ value=“/“  <?php echo ($operator == „/“) ? „checked“ : “; ?> > 
                    <label><h4>/</h4></label> 
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“Log10″ 
                      name=“operation“ value=“Log10″  <?php echo ($operator ==
                      „Log10“) ? „checked“ : “; ?> >  
                    <label><h4>log10(n1)</h4></label>
                    </td>
                </tr>   
                <tr>        
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“sin“ 
                     name=“operation“ value=“sin“  <?php echo ($operator == „sin“) ?
                     „checked“ : “; ?>  >  
                    <label><h4> sin(n1)</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“cos“ 
                      name=“operation“ value=“cos“  <?php echo ($operator == „cos“)
                        ? „checked“ : “; ?> > 
                    <label><h4>cos(n1)</h4></label> 
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“tg“ 
                     name=“operation“ value=“tg“  <?php echo ($operator == „tg“) ?
                      „checked“ : “; ?> >  
                    <label><h4>tg(n1)</h4></label>
                    </td>
                </tr>   
              </table>
            </div>
          <br>

          <button type=“submit“ name=“submit“ class=“btn btn-primary“> Calculate result </button>

          <?php   //($is_result == „true“) ? {          
                
                 if ($is_result && $msg == “) {
                    $result = number_format($result, 2, ‚,‘, ‚ ‚); // formating number refer to https://www.php.net/manual/en/function.number-format.php

                        echo „<br> <br>“;
                         echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h3> = $result</h3> <td>
                              </tr> „; 
                              echo “ </table> „;
                    
                    
                } ; 
                 ?>
                 <br>
                    
                     
                    <?php if($msg != “): ?>  <!– This part show error or warning message if one of the operand does not meet calculations requirements – dividing by zero –>
                        <br><br>    
                    <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
                    <?php endif; ?>
                    
      </form>

PHP code for result calculation follow

<?php
    // two variables for message and styling of the mesage with bootstrap
    $msg = “;
    $msgClass = “;

    // default values of auxiliary variables
    $operator = “; // at the beggining is no operator selected
    $is_result = „false“; //before hitting submit button no result is available
    $result = 0; // result and boath number are by default at zero values initialized


    // Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)){
        // Data obtained from $_POST are assigned to local variables
        $nr1 = htmlspecialchars($_POST[‚nr1‘]);
        $nr2 = htmlspecialchars($_POST[‚nr2‘]);
        $operator = htmlspecialchars($_POST[‚operation‘]); 
        
        $is_result = „true“;

        // calculation of appropriate results
        /* if ($operator == „+“) {          
            $result = $nr1 + $nr2;     
        };
        if ($operator == „-„) {          
            $result = $nr1 – $nr2;     
        };
        if ($operator == „*“) {          
            $result = $nr1 * $nr2;     
        };
        if ($operator == „/“) {          
            $result = $nr1 / $nr2;     
        };
        */
        //this part can be reworked for switch command for educational purposes like this
        switch ($operator) {
          case „+“: {          
                       $result = $nr1 + $nr2;     
                    }; break;
          case „-„: {          
                        $result = $nr1 – $nr2;     
                     }; break;
          case „*“: {          
                        $result = $nr1 * $nr2;     
                     }; break;
          case „/„: {   
                        if ($nr2 != 0)  { //dividing by zero mittigation, if nr2 is zero then
                                                      error message is outputed
                            $result = $nr1 / $nr2;
                            $msg = “;} 
                            else { 
                                $msg = ‚Dividing by zero NaN‘; // text of the message
                                $msgClass = ‚alert-danger‘; // bootstrap type alert-
                                                                                       danger is outputed
                             } ;  
                             
                     }; break;  
          case „Power“: {          
                        $result = Pow($nr1, $nr2);     
                     }; break;  
          case „Log10“: {          
                        $result = Log10($nr1);     
                     }; break;  
          case „sin“: {          
                        $result = sin($nr1);     
                     }; break;  
          case „cos“: {          
                        $result = cos($nr1);     
                     }; break;  
          case „tg“: {          
                        $result = tan($nr1);     
                     }; break;                       
        };
        
    }
?>
 

For main formating was used bootstrap code obtained from https://bootswatch.com/.

Small altering is created by own style.css that follow

.navbar  {
    background-color: #325d88;
    margin-bottom: 25px ;
    
}

.navbar-brand {
   
    color: white;
}

/* set midle container to width 580px */
.container {
   
    width: 580px;
    margin-left: 240px;
  
}

/* add margin to both sides in calculator input fields */
.inputSelector {
   
    
    margin-left: 20px;
    margin-right: 15px;
  
}




/* colorizing backround and change font-size of input number fields n1 and n2 partialy alter bootstrap css */
.form-control {
   
    background-color: rgb(250, 250, 131);
    font-size:25px
}

/* aboolute positioning of image on calc frontend – on left side */
#calcimage {
   
    position: absolute;
  top: 80px;
  left: 20px;
  right: 0;
  
  
}

/* change wight of label text before input field of form */
label {
   
    font-weight: bold;
}


.footer {
    background-color: #325d88;
    margin-top: 25px;
    padding-left: 15px;
    height: auto;
    
}

Full code for further study can be obtained from github here.

Share the article via the network
Translate »