会话变量未保留设置

时间:2014-12-19 05:10:45

标签: php session session-variables

基本上我试图将会话变量设置为布尔值,以确保用户无法完成两次函数。

session_start()
if(isset($_GET['vote'], $_GET['title'], $_GET['user']))
{
    if(isset($_SESSION[$_GET['title']]))
    {
        $_SESSION[$_GET['title']] = true;
    }
    else if(!isset($_SESSION[$_GET['title']]))
    {
        $_SESSION[$_GET['title']] = false;
        add_title_vote($_GET['title'], $_GET['vote'], $_GET['user']);
    }
}

此代码应该采用get方法发送的信息,然后根据一个get变量title创建一个新的会话变量。如果会话变量已存在,则应将变量设置为true。如果变量不存在,则会话变量设置为false,并调用依赖于会话变量值的函数。仅当会话变量为false时才会调用该函数。

如果会话变量为false,则调用该函数:

function add_title_vote($title, $vote, $user)
{
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "Assignments";
    $connection = new mysqli($servername, $username, $password, $dbname);
    if($_SESSION[$title] == false)
    {
    if($vote === 'up')
    {
    $sql = "UPDATE `mi4` SET `relevance` = `relevance` + 1 WHERE `title`='$title'";
    $servername1 = "localhost";
    $username1 = "root";
    $password1 = "";
    $dbname1 = "Users";
    $connection1 = new mysqli($servername1, $username1, $password1, $dbname1);
    mysqli_query($connection1, "UPDATE `login` SET `score` = `score` + 1 WHERE `user` = '$user'");
    }
    else if ($vote === 'down' && $votedown[$title] == false)
    {
    $sql = "UPDATE `mi4` SET `relevance` = `relevance` - 1 WHERE `title`='$title'";
    $servername1 = "localhost";
    $username1 = "root";
    $password1 = "";
    $dbname1 = "Users";
    $connection1 = new mysqli($servername1, $username1, $password1, $dbname1);
    mysqli_query($connection1, "UPDATE `login` SET `score` = `score` - 1 WHERE `user` = '$user'");
    }
    mysqli_query($connection, $sql);
    $_SESSION['voted'] = true;
    header("Location: /mi4.php");
    die();
    $_SESSION[$title] = true;
    }
}

由于某种原因,它总是说会话变量尚未设置,并在第一段代码中执行if语句的else if部分。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您在设置会话之前编写了die()

    mysqli_query($connection, $sql);
    $_SESSION['voted'] = true;
    header("Location: /mi4.php");
    die(); <--
    $_SESSION[$title] = true; 
    }
}

您可以将其删除或在会话后放置。这两种方式你都不需要它,因为你没有用它做任何事情。

答案 1 :(得分:0)

只需复制并粘贴即可。它有效。

session_start();
if(isset($_GET['vote'], $_GET['title'], $_GET['user']))
{
    if(isset($_SESSION[$_GET['title']]))
    {
        $_SESSION[$_GET['title']] = true;
    }
    else if(!isset($_SESSION[$_GET['title']]))
    {
        $_SESSION[$_GET['title']] = false;
        add_title_vote($_GET['title'], $_GET['vote'], $_GET['user']);
    }
}