我的代码中有什么问题我似乎无法通过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();
}
}
答案 0 :(得分:0)
我看不到你的班级名字,但是你可以这样做: 将参数添加到公共函数中并使用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();
}