Codeigniter Rest Api, whats wrong



我的代码中出了什么问题我似乎无法通过id显示数据库中的数据,当我转到http://localhost/server/index.php/api/example/users/id/1.xml链接时,它仍然显示数据库中的所有数据

控制器

         public function users_get()
{
    // Users from a data store e.g. database
    $users = 
    $result=$this->regusers->get();
    $id= $this->get('result');
    // If the id parameter doesn't exist return all the users
    if ($id === NULL)
    {
        // Check if the users data store contains users (in case the database result returns NULL)
        if ($users)
        {
            // Set the response and exit
            $this->response($users, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        }
        else
        {
            // Set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No users were found'
            ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
        }
    }
    // Find and return a single record for a particular user.
    $id = (int) $id;
    // Validate the id.
    if ($id <= 0)
    {
        // Invalid id, set the response and exit.
        $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
    // Get the user from the array, using the id as key for retreival.
    // Usually a model is to be used for this.
    $user = NULL;
    if (!empty($users))
    {
        foreach ($users as $key => $value)
        {
            if (isset($value['result']) && $value['result'] === $id)
            {
                $user = $value;
            }
        }
    }
    if (!empty($user))
    {
        $this->set_response($user, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
    }
    else
    {
        $this->set_response([
            'status' => FALSE,
            'message' => 'User could not be found'
        ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
    }
}

型号

<?php 
class Regusers Extends CI_Model{
public function get(){
    $query = $this->db->get('tbl_users');
    return $query->result();
   }
  }

我看不到你的类名,但你可以这样做:在公共函数中添加一个参数,并用url填充。

网址:http://localhost/server/index.php/api/users_get/ID_HERE

此外,请尽量只在您的模型中获取您想要的记录。不要自己循环浏览所有的记录。

控制器;

  public function users_get($id = null)
 {
 if($id === null){
 // GET ALL USERS
// Call here your model function to select all users
}else{
// GET USER WITH ID $id

// Call here your model function to select user by ID
}
}

模型;

// Get all users
public function get(){
$query = $this->db->get('tbl_users');
return $query->result();
}
// Get user based on ID
public function getById($id){
$query = $query = $this->db->get_where('tbl_users', array('id' => $id)
return $query->result();
}

最新更新