Manipulating values through Hidden input

Asked

Viewed 364 times

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 Séssion, but unsuccessfully:

<?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...";
}

?>
  • What’s missing? Which way out?

  • The history is missing, every calculation I do needs to appear the account on the same page, like the calculator in windows 10 and 8.I will edit with the picture of the calculator.

  • But what’s the exit from what’s been done so far?

  • The saaida is the result of the operation with the " echo $result " and the account made with " echo $_SESSION['historico']['valor1'] ." $operator ". $_SESSION['historico']['valor2'] ." = ". $result ; "

  • The idea is that every time I press the calculate button it shows the result of the account and adds from the page all accounts made without deleting the first account made.

  • You can create a history.txt file

  • And what I do in this file ?

  • @Lonetonberry gives a look

Show 3 more comments

3 answers

2

The code has several errors, see:

You are checking the variable $_POST["calcularbtn"], would not be $_SESSION["historico"]?

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

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

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

You are using the operator and the result you just saved. Ideally save them 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 variable $_SESSION["historico"] is an array of arrays, so you must iterate somehow about its elements:

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

See working on ideone.

  • This echo is wrong. Warning: Illegal string offset 'valor1' in C: xampp htdocs activities calculator.php on line 116

  • @Lonetonberry Can you show me how your code turned out?

  • I appreciate your help, but Attila also solved my problem.

1


Basically I store the history in a hidden input(Hidden).

The idea is to send your php script the updated value of the history field in a post variable. Once it arrives in your script it is concatenated with the string that represents the current operation.

Well, initially it is empty but after the first execution 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 only 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 whether the operations variables are set and adds the variable $histórico 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 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.

Complete 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>";
                   
        }
    
    ?>

   

Completion: 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 just as building it using php is not appropriate. But for educational purposes the use of hidden fields are quite useful to traffic data from the client to the server without the user having control over them.

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

  • Can you explain what’s going on here ?

  • 1

    I added information to the answer. I hope I’ve helped.

  • The problem is that the php script cannot be above the form because the results of the operations and the history appear below the form. And if I put this script you made under the form it gives error.

  • 1

    Just echo history below the form. See the edit

  • And why he’s wrong in case I use the echo below ?

  • I noticed that you put a "#" in the form action, What’s the need for this ?

  • Well I am running the script on the same page: action="#" . I hope you have put all this code in a single file. cal.php .. you only need one file in this case. Copy all the code to it and see working.

Show 3 more comments

0

With Session it would be 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 note 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>

Browser other questions tagged

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