Tuesday, August 25, 2015

Creating a Basic Calculator using PHP

<?php
$errors = array();
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){

    if(!isset($_POST['value1']) || trim($_POST['value1']) == ""){
        $errors[] = "You must enter first Number";
    } elseif(!is_numeric($_POST['value1'])) {
        $errors[] = "You must put numeric value in first number field";
    }else{
        $value1 =$_POST['value1'];
    }


    if(!isset($_POST['value2']) || trim($_POST['value1']) == ""){
        $errors[] = "You must enter Second Number";
    } elseif(!is_numeric($_POST['value2'])) {
        $errors[] = "You must put numeric value in 2nd number field";
    }else{
        $value2 =$_POST['value2'];
    }

    if(empty($_POST['value3'])){
        $errors[] = "You must enter a operator";
    }elseif( $_POST['value2'] == 0 && $_POST['value3'] == "/") {
        $errors[] = "Second Number can't be zero in division";
    } else {
        $operator =$_POST['value3'];
    }

    if(empty($errors)){
        if($operator == "+"){
            $result = $value1 + $value2;
        } elseif($operator == "-"){
            $result = $value1 - $value2;
        } elseif($operator == "*"){
            $result = $value1 * $value2;
        } elseif($operator == "/"){
            $result = $value1 / $value2;
        }else{
            $errors[] = "Currently our supporting operator is +-*/";
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            font-family: arial, sans-serif;
        }
        label {
            display: block;
        }
    </style>
</head>
<body>
<form action="" method="post">
    <label>First Number:</label>  <input type="text" name="value1" placeholder="Number one"><br><br>
    <label for="">Second Number:</label> <input type="text" name="value2" placeholder="Number Two"><br><br>
    <label for="">Operator(currently supported operator is +-*/):</label><input type="text" name="value3" placeholder="operator"><br><br>
    <input type="submit" name="submit" id="submit">
</form>
<div id="result">
    <?php
        if(isset($result)){
            echo $result;
        }
        if(isset($errors)){
            foreach($errors as $error){
                echo $error . "<br>";
            }

        }
    ?>
</div>
</body>
</html>

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }