Pregunta

this is my code

<?php
    if (!strtoupper($_SERVER['REQUEST_METHOD']) == 'POST'){ 
        $hdnNumber = rand(10, 500);}
    else
        if(isset($_POST["hiddenNumber"]))
            $hdnNumber = $_POST["hiddenNumber"];
    echo $hdnNumber ; 
    ?>        
<form action="" method="post">
        Number: <input type="text" name="number"><br>
        <input type="hidden" name="hiddenNumber" value="<?= $hdnNumber ?>" />
        <input type="submit" value="submit">
        </form>

I want to propagate the value of $hdnNumber on all form posts, and its value should be the random value generated on page load.

When I am submitting the form, it again creates a new random number, but I want to maintain the first value only.

Please help. Thanks in advance

¿Fue útil?

Solución

You should only set the value when the value is blank/unset, e.g.

$hdnNumber = isset($_POST['hiddenNumber']) ? $_POST['hiddenNumber'] : rand(10,500);

Otros consejos

To compliment Marc B's answer and the usage of a ternary operator, you can use sessions to pass on that (hidden) value to another page and any subsequent page when using sessions.

Sidenote: Although you can pass that (hidden) number in a second page using
$hdnNumber = $_POST['hiddenNumber']; you are limited to just that.

Should you want to use it for DB-related work, you could assign it to a session variable that can subsequently be used anywhere else thereafter.

This could prove to be useful when implemented into DB work.

HTML form

<?php
session_start();
// Borrowed from Marc B's answer
$hdnNumber = isset($_POST['hiddenNumber']) ? $_POST['hiddenNumber'] : rand(10,500); 
$_SESSION['hiddenNumber']=$hdnNumber;

// my own testing method
    if(isset($_POST['submit'])){
        echo $_SESSION['hiddenNumber'];
}
?>        
<form action="" method="post">
Number: <input type="text" name="number"><br>
<input type="hidden" name="hiddenNumber" value="<?= $hdnNumber ?>" />
<input type="submit" name="submit" value="submit">
</form>

<a href="hidden_session.php">Verify the number</a>

hidden_session.php

(will echo the number from the initial HTML form)

<?php
session_start();
$test=$_SESSION['hiddenNumber'];
echo $test;
?>
<a href="session_check2.php">Go here</a>

session_check2.php

(will echo the same number, initially coming from HTML form, that was passed on to the second page)

<?php
session_start();
$test=$_SESSION['hiddenNumber'];
echo $test;

Using echo $_SESSION['hiddenNumber']; will also work.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top