只有重新加载网页后,投票结果才会更新

时间:2018-12-25 16:01:32

标签: php mysql cookies pdo sql-update

我想使用PHP + MySQL创建样本投票表决系统。我从数据库中获取结果,但是仅在重新加载页面后才显示更新的结果,否则,提交投票后,将显示旧结果。我知道重新加载后考虑到Cookie的某些有趣行为。 但是我的问题是,当用户第一次输入投票时,会打印一条“谢谢”消息,然后显示投票结果。 在这部分中,我也必须重新加载页面才能查看正确的轮询结果。为什么?对于第一次投票,我不应该拥有任何Cookie。

<?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;
}

我如何摆脱这个问题?我已经检查了数据库,单击民意调查html页面上的发布按钮后,数据库立即更新。但是,只有在我重新加载页面后,才能显示是和否的正确结果。

0 个答案:

没有答案