仅当我重新加载网页时才更新投票结果

zsbz8rwp  于 2021-06-17  发布在  Mysql
关注(0)|答案(0)|浏览(148)

这个问题在这里已经有答案了

php-cookie变量和会话变量的有趣行为(3个答案)
引用-这个错误在php中是什么意思(36个答案)
php Cookie在两页之间传递变量[重复](2个答案)
两年前关门了。
我想用php+mysql做一个示例投票系统。我从数据库中获得结果,但更新后的结果只有在我重新加载页面后才会显示,否则,在提交投票后,会显示旧的结果。我知道有一些有趣的行为饼干考虑后重新加载。但我的问题是,当用户第一次输入投票时,会打印一条感谢消息,然后显示投票结果。在这一部分中,我也必须重新加载页面才能看到正确的投票结果。为什么?第一次投票,我不应该吃饼干。

<?php
//complete code for poll.class.php.php
include_once "models/poll.class.php";   // getting class 'poll'
$poll = new poll($db);     // declaring new object of class of 'poll'; pass PDO object as argument
$pollData = $poll->getPollData();   //getting polldata

if (isset($_COOKIE['voted']))   //check if the user has already voted by cookies
{
    echo "You already voted  ".$_COOKIE['voted'];

}

else
{
    $isPollSubmitted =  isset($_POST['user-input']);    //check if the form was submitted
    if ($isPollSubmitted)   //if the form is just submitted
    {
        $input = $_POST['user-input'];  //take the casted vote
        $voteSubmitted = $poll->updatePoll($input);  //and update the result
        if ($voteSubmitted)
            setcookie('voted', $input, time()+1*60, '/');

        echo "Thanks for your Vote. You voted $input";
        /*if (isset($_COOKIE['voted']))
        {
            echo $_COOKIE['voted'];
        }*/
    }
    else
    {
        $pollAsHTML = include_once "views/poll-html.php";   // getting and creating view of poll result from views folder
        echo $pollAsHTML;
    }

}
return showPollData();

function showPollData()
{
    global $pollData;
    return "<h1>Poll results</h1>
            <ul>
            <li> $pollData->yes said yes</li>
            <li>$pollData->no said no</li>
            </ul>";
}
?>

这是我的 getPollData()poll.class.php :

public function getPollData()
    { 
    //the actual SQL statement
    $sql = "SELECT * FROM poll WHERE poll_id = 1";
    //Use the PDO connection to create a PDOStatement object
    $statement = $this->db->prepare($sql);
    // execute SQL statement
    $statement->execute();
    //retrieve the first row of the table
    $pollData = $statement->fetchObject();
    return $pollData;

      }

还有 updatePoll() 功能:

public function updatePoll($input)
{
    $updatePollResultSQL = "";
    if ($input == 'yes')
        $updatePollResultSQL = "UPDATE poll SET yes = yes + 1 WHERE poll_id = 1";
    elseif  ($input == 'no')
        $updatePollResultSQL = "UPDATE poll SET no = no + 1 WHERE poll_id = 1";
    $updateStatement = $this->db->prepare($updatePollResultSQL);
    $updateStatement->execute();
    return true;
}

我怎样才能解决这个问题?我已经检查了我的数据库,它在我单击poll html页面上的post按钮后立即更新。但是只有在我重新加载页面后,才会显示正确的“是”和“否”投票结果。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题