get方法无法在php rest web服务上运行

时间:2014-06-26 03:48:34

标签: php mysql rest

对不起,我尝试使用请求方法POST和GET进行宁静的Web服务,我最终成功使用GET方法查看mysql上的数据,但是当我使用POST方法搜索数据或删除数据时,任何用POST方法都无法正常工作。我不知道为什么......谢谢这个

private function users(){
    // Cross validation if the request method is GET else it will return "Not Acceptable" status
    if($this->get_request_method() != "GET") {
        $this->response('',406);
    }
    $sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
    if(mysql_num_rows($sql) > 0) {
        $result = array();
        while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC)){
            $result[] = $rlt;
        }
        // If success everythig is good send header as "OK" and return list of users in JSON format
        $this->response($this->json($result), 200);
    }
    $this->response('',204);    // If no records "No Content" status
}

然后DELETE方法

private function deleteUser() {
    // Cross validation if the request method is DELETE else it will return "Not Acceptable" status
    if($this->get_request_method() != "DELETE"){
        $this->response('',406);
    }
    $id = (int)$this->_request['id'];
    if($id > 0) {
        mysql_query("DELETE FROM users WHERE user_id = $id");
        $success = array('status' => "Success", "msg" => "Successfully one record deleted.");
        $this->response($this->json($success),200);
    } else
        $this->response('',204);    // If no records "No Content" status
}

1 个答案:

答案 0 :(得分:1)

您的users()和deleteUser()函数分别专门检查GET和DELETE的REQUEST_METHOD。因此,如果在POST完成后调用其中任何一个函数,它们都将返回406

更新:回答评论:我该怎么做才能解决这个问题?

如果期望相同的函数与POST一起使用,以及它们各自的主要REQUEST_METHOD,那么您需要允许验证POST请求方法。

private function users(){
    // Cross validation if the request method is GET else it will return "Not Acceptable" status
    if ($this->get_request_method() != 'GET' && $this->get_request_method() != 'POST')  {
        $this->response('',406);
    }

private function deleteUser() {
    // Cross validation if the request method is DELETE else it will return "Not Acceptable" status
    if ($this->get_request_method() != 'DELETE' && $this->get_request_method() != 'POST') {
        $this->response('',406);
    }

对于deleteUser函数,我假设$this->_request来自$ _REQUEST,并且可以从查询字符串或表单帖子中选择id。< / p>

由于您只显示了这两项功能,因此如果请求是POST,我无法确定其他代码是否会将操作重定向到其他位置。