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 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常