增加和重置PHP会话变量

时间:2015-09-17 22:15:46

标签: php

我试图在使用PHP会话变量的测验中保持得分。我希望得分为正确答案递增,如果您选择跳过问题则重置为0。正确跳过将其重置为0,但是对于连续的正确答案,得分不会超过1。这是session_start()部分:

<?php
session_start();
if (!isset($_SESSION['score'])) 
    $_SESSION['score'] = 0;

if (!isset($_SESSION['skipped'])) 
    $_SESSION['skipped'] = FALSE;

if($_SESSION['skipped'] == TRUE){
    $_SESSION['score'] = 0;
    $_SESSION['skipped'] = !$_SESSION['skipped'];
}
?>

添加到分数的逻辑:

<script>
        var key = <?php echo json_encode($rand_key) ?>;

        function my_submit(curr) {
            var info = curr.guess.value;

            if (key.toLowerCase()==info.toLowerCase()){
                <?php
                    $x = $_SESSION['score'] + 1;
                    $_SESSION['score'] = $x;
                ?>

                var up_score = <?php echo json_encode($x) ?>;
                alert('Correct! Score: ' + up_score);
                return true;
            }

                alert('Incorrect!');
                return false;

        }
    </script>

重置分数:

<script>
        var answer = <?php echo json_encode($rand_key) ?>;

        function skipped(){
            <?php
                    $q = TRUE;
                    $_SESSION['skipped'] = $q;
                ?>
            alert('Correct answer: ' + answer + '. Your score has been reset for skipping.');
            return true;
        }

    </script>

这个网站提供了令人难以置信的帮助;感谢所有的帮助!

1 个答案:

答案 0 :(得分:1)

您在一些JavaScript函数中编写PHP,就好像您希望它由JavaScript本身执行一样。

如果你删除了HTML / JS输出,你可以在加载页面时看到服务器上实际发生了什么(我假设你的代码片段是有序的):

session_start();
if (!isset($_SESSION['score'])) 
    $_SESSION['score'] = 0;

if (!isset($_SESSION['skipped'])) 
    $_SESSION['skipped'] = FALSE;

if($_SESSION['skipped'] == TRUE){
    $_SESSION['score'] = 0;
    $_SESSION['skipped'] = !$_SESSION['skipped'];
}
$x = $_SESSION['score'] + 1;
$_SESSION['score'] = $x;

$q = TRUE;
$_SESSION['skipped'] = $q;

在第一页加载空会话时,这会将$_SESSION['score']设置为0(因为它尚未设置),然后将其增加到1,然后将$_SESSION['skipped']设为true

在后续页面加载时,会将$_SESSION['score']设置为0(因为已设置跳过),然后再将其递增到1并最终设置{再次{1}}到skipped(你看:没有改变)