Manipulating values through input hidden

0

I made a calculator as follows:

<?php
if (isset($_POST['calcularbtn'])) {

    $valor1 = $_POST['valor1'];
    $valor2 = $_POST['valor2'];
    $tipo   = $_POST['tipo'];

    if ($tipo == 'Somar') {

        $operador  = '+';
        $resultado = $valor1 + $valor2;

    } elseif ($tipo == 'Subtrair') {

        $operador  = '-';
        $resultado = $valor1 - $valor2;

    } elseif ($tipo == 'Multiplicar') {

        $operador  = '*';
        $resultado = $valor1 * $valor2;

    } elseif ($tipo == 'Dividir') {

        $operador  = '/';
        $resultado = $valor1 / $valor2;

    } elseif ($tipo == 'Potência') {

        $resultado = pow($valor1, $valor2);

    } else {

        $resultado = pow($valor1, 1 / 2);
    }

    echo $resultado;
} else {
    echo "Esperando cálculo...";
}
?>

It works, but now the difficulty is to save all the accounts and do something like a history to make the display. I tried with session, but without success:

<?php
session_start();

if (isset($_POST['calcularbtn'])) {
    $_SESSION['historico'] = array(
        'valor1' => $_POST['valor1'],
        'valor2' => $_POST['valor2']
    );

    echo $_SESSION['historico']['valor1'] . " $operador " . $_SESSION['historico']['valor2'] . " = " . $resultado;
} else {
    echo "Sem operações realizadas...";
}

?>
    
asked by anonymous 21.04.2018 / 22:22

3 answers

1

I basically store the history in a hidden input.

The idea is to send to your php script the updated value of the historical field in a post variable. Once it arrives in your script it is concatenated with the string representing the current and echoed operation.

Well, initially it is empty but after the first run it starts to accumulate the history contained in the input:

 $historico = $_POST['historico'] . '</br>' . $valor1 . $operador . $valor2 . '=' . $resultado ;  

So the value inside the input is being updated:

<input hidden="" type="text" name="historico" value="<?php if (isset($historico)) { echo $historico; } ?>" > 

I've just added this block inside your if:

 if(isset($valor2) && isset($valor1) && isset($operador)){
            $historico = $_POST['historico'] . '</br>' . $valor1 . $operador . $valor2 . '=' . $resultado ;           
            echo $historico;
            echo "</br>";

        }

It checks if the operations variables are set and adds the variable $histórico to the value of the hidden input:

<input hidden="" type="text" name="historico" value="<?php if (isset($historico)) { echo $historico; } ?>" >

This field has the function of sending to your php script the history to be concatenated with '</br>' . $valor1 . $operador . $valor2 . '=' . $resultado ;

Note that I use isset so there are no empty variable alerts when they are not set.

Full Code

<?php  

if ( isset($_POST['calcularbtn']) ) {

        $valor1 = $_POST['valor1'];
        $valor2 = $_POST['valor2'];
        $tipo = $_POST['tipo'];

        if ($tipo == 'Somar') {

            $operador = '+';
            $resultado = $valor1 + $valor2;

            }elseif ($tipo == 'Subtrair') {

            $operador = '-';
            $resultado = $valor1 - $valor2;

            }elseif ($tipo == 'Multiplicar') {

            $operador = '*';
            $resultado = $valor1 * $valor2;

            }elseif ($tipo == 'Dividir') {

            $operador = '/';
            $resultado = $valor1 / $valor2;

            }elseif ($tipo == 'Potência') {

            $resultado = pow($valor1, $valor2);

            }else{
            $resultado = pow($valor1, 1/2);

            }
                echo 'Resultado=' .  $resultado;   
            }else{
               echo "Esperando cálculo...";
            }        
         if(isset($valor2) && isset($valor1) && isset($operador)){
           $historico = $_POST['historico'] . '</br>' . $valor1 . $operador . $valor2 . '=' . $resultado ;
       }

    ?>

    <form class="form-signin" method="post" action="#">
        <div class="form-label-group">
            <input hidden="" type="text" name="historico" value="<?php if (isset($historico)) { echo $historico; } ?>" >
            <input class="form-control" type="number" name="valor1"  size="5" placeholder="Valor 1"><br>
            <select class="custom-select d-block w-100" name="tipo" >
                <option selected="selected">Somar</option>
                <option>Subtrair</option>
                <option>Multiplicar</option>
                <option>Dividir</option>
                <option>Potência</option>
                <option>Raiz Quadrada</option>
            </select><br><br>
        </div>
        <div class="form-label-group">
            <input class="form-control" type="number" name="valor2"  size="5" placeholder="Valor 2"><br>
        </div>
        <input class="btn btn-outline-secondary" type="submit" name="calcularbtn" value="Calcular">
    </form>'

<?php

    if(isset($historico)){          
          echo $historico;
          echo "</br>";

        }

    ?>

Conclusion : There are a billion ways to do this. But there are more appropriate ways. This is not the most appropriate way to build a calculator using php as well as building this using php is not appropriate. However for teaching purposes the use of hidden fields are quite useful for transferring data from the client to the server without the user having control over them.

Tip: Use javascript with it you can leave the process dynamic and use more resources. Think: why ask the server for something that your browser already knows. Ask the browser about javascript and it will know very well what to do with your data. In addition, of course, not having to reload the same page to get the result.

    
21.04.2018 / 23:04
2

The code has several errors, see:

Are you checking the $_POST["calcularbtn"] variable, would not it be $_SESSION["historico"] ?

if (isset($_SESSION["historico"]))

You're overwriting the value of the variable, the right thing would be to use array_push , or your shorthand:

$_SESSION["historico"][] = array(/* criação de novo elemento aqui */)

You are using the operator and result you just saved. The ideal would be to save them next to the values in the session variable:

$_SESSION["historico"][] = [
        'valor1' => $_POST['valor1'], 
        'valor2' => $_POST['valor2'],
        'operador' => $operador,
        'resultado' => $resultado
    ];

You are printing only what has just been saved, remember that the variable $_SESSION["historico"] is an array of arrays, so you must iterate in some way about its elements:

foreach ($_SESSION["historico"] as $key => $value ){
    echo "{$value["valor1"]} {$value["operador"]} {$value["valor2"]} = {$value["resultado"]}\n";
}

See working at ideone .

    
21.04.2018 / 23:00
0

With session would look like this:

PHP

session_start();                   

if ( isset($_POST['calcularbtn']) ) {

    $valor1 = $_POST['valor1'];
    $valor2 = $_POST['valor2'];
    $tipo = $_POST['tipo'];

    if($tipo  == '+'){
       $resultado = $valor1 + $valor2;
    }else if ($tipo == '-'){
       $resultado = $valor1 - $valor2;
    }else if($tipo == '*'){
       $resultado = $valor1*$valor2;
    }else if($tipo == '/'){
       $resultado = $valor1/$valor2;
    }else if($tipo == 'pow'){
       $resultado = pow($valor1, $valor2);
    }else{
       $resultado = pow($valor1, 1 / 2);
    }
    //resultado da operação
    echo "<span style='color:red'>".$resultado."</span>";
    echo "<br>";

    //armazenando valores no array 
    $_SESSION['historico'][] = $valor1.",".$tipo.",".$valor2.",".$resultado;

    //imprime a session para simples verificação podendo ser retirada do código
    print_r($_SESSION['historico']);

    echo "<ul>";

    //itera para apresentação do historico
    foreach($_SESSION['historico'] as $list){

        $parte = explode(",", $list);

        if ($parte[1]=="pow" && $parte[3]!="1/2") {
            echo "<li>".$parte[0]."<sup>2</sup>=".$parte[3]."</li>";
        }else if($parte[1]=="1/2"){
            echo "<li>".$parte[0]."<sup>1/2</sup>=".$parte[3]."</li>";
        }else{
            echo "<li>".$parte[0].$parte[1].$parte[2]."=".$parte[3]."</li>";
        }
    }

     echo "</ul>";

}else{
    echo "Esperando cálculo...";
}

HTML Notice that options contain value

<form class="form-signin" method="post" action="">
<div class="form-label-group">
   <input class="form-control" type="number" name="valor1" size="5" placeholder="Valor 1"><br>
   <select class="custom-select d-block w-100" name="tipo" >
       <option selected="selected" value="+">Somar</option>
       <option value="-">Subtrair</option>
       <option value="*">Multiplicar</option>
       <option value="/">Dividir</option>
       <option value="pow">Potência</option>
       <option value="1/2">Raiz Quadrada</option>
   </select><br><br>
</div>
<div class="form-label-group">
  <input class="form-control" type="number" name="valor2" size="5" placeholder="Valor 2"><br>
</div>
  <input class="btn btn-outline-secondary" type="submit" name="calcularbtn" value="Calcular">
</form>
    
22.04.2018 / 04:48