How to read what the user typed in a form?

3

The code looks like this:

<form method="post" action="pagina.php"/>
<?php
$c= 1;
$neg = 0;
    while($c <=3){
        echo "Digite um numero: <input type='number' name='$num' min='1'/>";
            if($num < $neg){
                $total++;
                }
            $c++;
            }
?>
<input type='submit' value='Resultado'/>

I'm not sure how to do what the user typed in, it becomes a variable so I can use the control structure on it. I tried putting a direct variable in name ($ num), but it does not seem to work or it does not work. Or is this kind of thing for JavaScript?

    
asked by anonymous 29.09.2016 / 01:12

2 answers

4

A simple example of dynamically generated form with PHP:

page_um.php

<form method="post" action="pagina_dois.php">
<?php
    for( $c = 1; $c <= 3; ++$c) {
        echo "   Digite um numero: <input type='text' name='input_$n'>";
    }
?>
   <input type='submit' value='Resultado'>
</form>

page_dois.php

<?php
    $total = 0;
    for( $c = 1; $c <= 3; ++$c) {
        $total = $total + $_POST["input_$n"];
    }
    echo "O total é $total";
?>

Note that there are two steps. The first, generating the form. The second, receiving the result of the form.

I did not do any protection to verify that the data makes sense, for being just an elementary example. In a practical application, you need a lot of extra care.

Basically, when you have a form with method POST , you have to catch using the global variable $_POST['nomedocampo'] .

    
29.09.2016 / 01:52
1

If you want to get what the user typed in pagina.php , just use PHP's GET or POST methods! Since you have declared the POST method on the form, just call the $_POST[''] function on pagina.php .

You can also do this with JavaScript, but on the same page, creating intervals of a few seconds, you can create a preview of the text that the user has made.

  • Tip

Remove the php code from your form, this code does not make sense! And create a input normal HTML, and name , put it to your preference. Like "number" for example.

Examples

PHP (page.php)

$number = $_POST['number'];
echo ($number);
//vai aparecer o que o usuário digitou ao clicar no Resultado.

JavaScript (form page)

$("#butaum").click(function() {

  var number = $('#number').val();

  $("#resultado").html(number);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><inputtype='number'id="number" name='number' min='1'>
</form>

<button id="butaum" >Resultado</button>

<div id="resultado">


</div>
    
29.09.2016 / 01:50