Home > Backend Development > PHP Tutorial > PHP submits a form rand without overwriting the previous one?

PHP submits a form rand without overwriting the previous one?

WBOY
Release: 2016-09-05 08:59:58
Original
1230 people have browsed it

<code>$s1 = rand(1,9);
$s2 = rand(1,9);

if($_POST['daan']){
    if($_POST['daan'] == $s1+$s2){
        $txt = '正确';
    }else{
        $s = $s1 + $s2;
        $txt = '错,正确答案是' .$s;
    }
}
</code>
Copy after login
Copy after login

?>

<code><?=$s1?> + <?=$s2?> = <input type="input" name="daan" />
<?=isset($txt) ? $txt : '请回答'?>
<input type="submit" name="button" id="button" value="提交" /></code>
Copy after login
Copy after login

The code is as above. The current situation is that after submitting the form, the rand value is the value after submission, causing the answer to be wrong. What can I do to avoid overwriting the last rand value?

Reply content:

<code>$s1 = rand(1,9);
$s2 = rand(1,9);

if($_POST['daan']){
    if($_POST['daan'] == $s1+$s2){
        $txt = '正确';
    }else{
        $s = $s1 + $s2;
        $txt = '错,正确答案是' .$s;
    }
}
</code>
Copy after login
Copy after login

?>

<code><?=$s1?> + <?=$s2?> = <input type="input" name="daan" />
<?=isset($txt) ? $txt : '请回答'?>
<input type="submit" name="button" id="button" value="提交" /></code>
Copy after login
Copy after login

The code is as above. The current situation is that after submitting the form, the rand value is the value after submission, causing the answer to be wrong. What can I do to avoid overwriting the last rand value?

<code>session_start();
if($_POST['daan']){
    if($_POST['daan'] == $_SESSION['result']){
        $txt = '正确';
    }else{
        $txt = '错,正确答案是' .$_SESSION['result'];
    }
}else{
    $s1 = rand(1,9);
    $s2 = rand(1,9);
    $_SESSION['result'] = $s1 + $s2;
}</code>
Copy after login

After you submit the form, the page will refresh again, and $s1 and $s2 will re-obtain a random value.
The way to solve the problem is to not change the value when it is refreshed. You put it in session Just stay inside.

<code class="php">session_start();
$s1 = $_SESSION['s1'] = rand(1, 9);
$s2 = $_SESSION['s2'] = rand(1, 9);

//然后下面的判断用$_SESSION的值就行了</code>
Copy after login

When refreshing, $_SESSION[], like a variable, will get a new value.

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template