Calculator in php using buttons

Asked

Viewed 1,169 times

0

I am new with PHP and I am making a calculator using buttons and I am having error, I would like to know the reason for the error, so far only did the sum and subtraction part.

<!doctype html>
<html lang="pt-br">

<head>
    <title>Resultado</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>

<?php

  $n1 = $_GET['numero1'];
  $n2 = $_GET['numero2'];
  $op = $_GET['escolha'];

    switch ($escolha){
        case = 'Soma':
            $result = $n1 + $n2;
            echo "O Resultado é: $result"; 
            break;
        case ='Subtração':
            $result = $n1 + $n2;
            echo "O Resultado é: $result"; 
            break; 
        }


?>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
</body>

</html>

Form

<!doctype html>
<html lang="pt-br">

<head>
    <title>Calculado Boladonaaa</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>

    <div class="container">
        <div clas="row">

            <div clas="col-md-6">

                <form id="formulario" name="formulario" method="get"
                                          action="resultado.php">
                    <h3>Calculada</h3>
                    <div class="form-group">
                        <label for="numero1">Digite um número para calculo</label>
                        <input type="number" class="form-control" name="numero1" id="numero1"
                            placeholder="Digite o primeiro número">
                    </div>
                    <div class="form-group">
                        <label for="numero2">Digite o segundo número para o calculo</label>
                        <input type="number" class="form-control" name="numero2" id="numero2"
                            placeholder="Digite o segundo número"><br>
                   </div>
                    <h4>Selecione a operação desejada<h4>        
                    <input class="btn btn-danger" type="submit" name="operacao" value="Soma" id="Soma">
                    <input class="btn btn-primary" type="submit"  name="operacao" value="Subtração" id="Subtração">
                    <input class="btn btn-success" type="submit"   name="operacao" value="Multiplicação" id="Multiplicação">
                    <input class="btn btn-warning" type="submit" name="operacao" value="Divisão" id="Divisão">
                  </form>         
            </div>

        </div>

    </div>








    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
</body>

</html>
  • The result page.php is returning not found - 404 Error.

  • And, by the way, what’s the mistake?

  • ( ! ) Parse error: syntax error, Unexpected '=' in C: wamp64 www project_calculated result.php on line 24, in the sum case line.

  • This equal does not exist, see documentation.

3 answers

2

I’m seeing some problems in your code:

$op = $_GET['escolha']; # esta jogando o escolha para a var $op
switch ($escolha) # esta usando $escolha que não existe
# case = 'Soma': # errado
case 'Soma': # correto
# seu switch falta um default:

Applying the changes:

$n1 = isset($_GET['numero1']) ? $_GET['numero1']*1 : 0 ; # verifico se o get foi passado e converto para inteiro fazendo o *1
$n2 = isset($_GET['numero2']) ? $_GET['numero2']*1 : 0 ;
$op = isset($_GET['escolha']) ? $_GET['escolha'] : 0 ;

switch ($op){ # corrigido

    case 'Soma': # corrigido
        $result = $n1 + $n2;
        echo "O Resultado é: $result"; 
        break;

    case 'Subtração': # corrigido
        $result = $n1 - $n2; # corrigido
        echo "O Resultado é: $result"; 
        break; 

    default: # adicionado
        echo "Sem resultado";
}

Editing:

As commented by @Andersoncarloswoss, you can convert to int/float using php functions intval and floatval

# esta linha esta fazendo o mesmo que o if abaixo
$n1 = isset($_GET['numero1']) ? $_GET['numero1']*1 : 0;

#  $var = <checagem> ? <valor caso verdade> : <valor caso falso>;


if( isset($_GET['numero1']) )
{
    $n1 = $_GET['numero1'] * 1;
    # O vezes (*) 1 era para transformar o valor para inteiro 
    # voce pode utilizar intval( $_GET['numero1'] ) para inteiro
    # ou ainda floatval( $_GET['numero1'] ) para float 
    # fiz isso pq o valor esta vindo por GET então acredito que nesse momento ele é string
    # mas aparentemente quando você aplicar a soma ou a subtração ...
    # ele vai tratar como numero como o @AndersonCarlosWoss disse em seu comentário
}
else
{
    $n1 = 0;
}

@Lucas: Thanks really, I made the changes, it worked but now only this adding even when I click subtraction
I think that part might be causing the problem

<input class="btn btn-danger" type="submit" name="operacao" value="Soma" id="Soma">
<input class="btn btn-primary" type="submit"  name="operacao" value="Subtração" id="Subtração">
<input class="btn btn-success" type="submit"   name="operacao" value="Multiplicação" id="Multiplicação">
<input class="btn btn-warning" type="submit" name="operacao" value="Divisão" id="Divisão">

One solution would be to put the type='radio' and create another input to do Submit, something like in the example below.

<label>
    <input type="radio" name="operacao" value="Soma" id="Soma">
    Soma
</label>
<label>
    <input type="radio" name="operacao" value="Subtração" id="Subtração">
    Subtração
</label>
<label>
    <input type="radio" name="operacao" value="Multiplicação" id="Multiplicação">
    Multiplicação
</label>
<label>
    <input type="radio" name="operacao" value="Divisão" id="Divisão">
    Divisão
</label>

<input type='submit' value='Enviar'>
  • 1

    What +$_GET['numero2']*1 ago?

  • My mistake, was to convert to whole, but do not remember if the php accepts the conversion +$var

  • I ended up changing last minute to $var*1

  • 1

    To my mind, wear intval or floatval would be more explicit than multiplying by "a random value", disregarding the fact that PHP already treats strings numbers as numbers, then conversion becomes unnecessary.

  • Thanks even, I made the changes, it worked but now only this adding even when I click subtraction

  • 1

    And I did not understand this "? $_GET['numero1']*1 : 0 ;" which was added next to the variables

  • @Lucasalmeida I made a change in response, check if it meets

Show 2 more comments

1

Instead of case = 'Soma', the right case is 'Soma'

        switch ($variable) {
        case 'value':
            # code...
            break;

        default:
            # code...
            break;
    }
  • Vlw, I’ve already corrected

0

 switch ($escolha){
        case 'Soma':
            $result = $n1 + $n2;
            echo "O Resultado é: $result"; 
            break;
        case 'Subtração':
            $result = $n1 + $n2;
            echo "O Resultado é: $result"; 
            break; 
        }

Your problem is in the case you are using assignment and the syntax is as follows in the above code!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.