dongwo5686 2017-06-22 03:26
浏览 31
已采纳

需要有关PHP网站逻辑的帮助

I am creating a contest website on my localhost using PHP. The project works as follows:

The user can log in and is directed to a page level.php?n=getUserData()['level'] , the logic is that if the user submits the right answer the user is redirected to the next level and the level field in the database must be updated so that the user can redirected to the next level level.php?n=2 and so on...., during login the users credentials are being stored in a session variable.(user_id,level,email ..etc).

My login controller:

include 'core/init.php';

$id = isset($_GET['n']) ? $_GET['n'] : null;
$validate = new Validator;
$template = new Template("templates/question.php");
$template->title = $validate->getQuestion($id)->body;
//$template->answer  = $validate->getQuestion($id)->answer;
$userid = getUserData()['user_id'];
if(isset($_POST['submit']))
{
    //  echo getUserData()['level']; die();
    $data = array();
    $data['answer'] = $_POST['answer'];
    $required_fields  = array("answer");
    if($validate->isRequired($required_fields))
    {
        if($validate->check_answer($_POST['answer']))
        {
            if($validate->update_level($userid)) 
            {
                redirect("level.php?n=".getUserData()['level'],"Correct Anwser","success"); 
            }

        }
        else
        {
            redirect("level.php?n=".getUserData()['level'],"Incorrect","error");
        }
    }
    else
        {
            redirect("level.php?n=".getUserData()['level'],"Empty","error");
        }

}

echo $template;

?>

`

My Validation class:

    <?php
    class Validator
    {
        private $db;

        public function __construct()
        {
            $this->db = new Database;
        }
        public function isrequired($field_array)
        {
            foreach($field_array as $field)
            {
                if(empty($_POST[''.$field.'']))
                {
                    return false;
                }
            }
            return true;
        }

        public function login($username,$password)
        {
            $this->db->query("SELECT * FROM users WHERE username=:username AND password=:password");
            $this->db->bind(":username",$username);
            $this->db->bind(":password",$password);
            $result = $this->db->single();
            $row = $this->db->rowCount();
            if($row>0)
            {
                $this->getData($result);
                return true;
            }
            else
            {
                return false;

            }
        }
        public function getData($row)
        {
            $_SESSION['is_logged_in'] = true;
            $_SESSION['user_id'] = $row->id;
            $_SESSION['username'] = $row->username;
            $_SESSION['email'] = $row->email;
            $_SESSION['level'] = $row->level;
        }

        public function getQuestion($id)
        {
            $this->db->query("SELECT * FROM question WHERE question_id = :id");
            $this->db->bind(":id",$id);
            $result = $this->db->single();
            return $result;
        }

        public function logout()
        {
            unset($_SESSION['is_logged_in']); 
            unset($_SESSION['username']);
            unset($_SESSION['user_id']); 
            unset($_SESSION['email']);
            return true;
        }

        public function update_level($id)
        {
            $level = getUserData()['level']+1;
            $this->db->query("UPDATE users SET level = :level WHERE id = :id");
            $this->db->bind(":level",$level);
            $this->db->bind(":id",getUserData()['user_id']);
            $this->db->execute();
            return true;    
        }
        function check_answer($answer)
        {
            $this->db->query("SELECT * FROM question WHERE correct = :answer");
            $this->db->bind(":answer",$answer);
            $row = $this->db->single();
            return $row;

        }
    }

    ?>

The getUserData() function:

function getUserData()
{
    $userarray = array();
    $userarray['username'] = $_SESSION['username'];
    $userarray['user_id'] = $_SESSION['user_id'];
    $userarray['email'] = $_SESSION['email'];
    $userarray['level'] = $_SESSION['level'];
    return $userarray;
}
  • 写回答

1条回答 默认 最新

  • douzhang7184 2017-06-22 16:23
    关注

    I believe your problem is in your update portion when the user gets the answer correct. You need to update your session. I suggest you rework your script to convert the getUserData() into a User class or similar:

    include('core/init.php');
    $id     =   (isset($_GET['n']))? $_GET['n'] : null;
    $validate   =   new Validator;
    $template   =   new Template("templates/question.php");
    # Create User class
    $User       =   new User();
    # Create make sure you set the files to internal array
    $User->init();
    # Start template
    $template->title = $validate->getQuestion($id)->body;
    # Fetch the id here
    $userid = $User->getUserId();
    # Check post
    if(isset($_POST['submit'])) {
        $data = array();
        $data['answer'] = $_POST['answer'];
        $required_fields  = array("answer");
        if($validate->isRequired($required_fields)) {
            if($validate->check_answer($_POST['answer'])) {
                # Update the database
                if($validate->update_level($userid)) {
                    # Increment the init() here to push the level up
                    redirect("level.php?n=".$User->init(1)->getLevel(),"Correct Anwser","success"); 
                }
    
            }
            else {
                # Since you are not updating, don't need the init() here
                redirect("level.php?n=".$User->getLevel(),"Incorrect","error");
            }
        }
        else {
                # Since you are not updating, don't need the init() here
                redirect("level.php?n=".$User->getLevel(),"Empty","error");
        }
    }
    
    echo $template;
    

    Create a user class

    User Class

    <?php
    class User
        {
            private $userData;
            public function init($increment = 0)
                {
                    # Get the current level
                    $level  =   $_SESSION['level'];
                    # If there is an increment
                    if($increment > 0) {
                        # Increment the level
                        $level += $increment;
                        # !!!***Re-assign the session***!!!
                        $_SESSION['level']  =   $level;
                    }
                    # Save the internal array
                    $userarray['username'] = $_SESSION['username'];
                    $userarray['user_id'] = $_SESSION['user_id'];
                    $userarray['email'] = $_SESSION['email'];
                    # Level will be set by variable now
                    $userarray['level'] = $level;
                    # Save to array
                    $this->userData =  (object) $userarray;
                    # Return object for chaining
                    return $this;
                }
            # This will call data from your internal array dynamically
            public function __call($name,$args=false)
                {
                    # Strip off the "get" from the method
                    $name       =   preg_replace('/^get/','',$name);
                    # Split method name by upper case
                    $getMethod  =   preg_split('/(?=[A-Z])/', $name, -1, PREG_SPLIT_NO_EMPTY);
                    # Create a variable from that split
                    $getKey     =   strtolower(implode('_',$getMethod));
                    # Checks if there is a key with this split name
                    if(isset($this->userData->{$getKey}))
                        $getDataSet =   $this->userData->{$getKey};
                    # Checks if there is a key with the raw name (no get though)
                    elseif(isset($this->userData->{$name}))
                        $getDataSet =   $this->userData->{$name};
                    # Returns value or bool/false
                    return (isset($getDataSet))? $getDataSet : false;
                }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab