2012-02-29 62 views
0

我测试笨的REST模块, 这里是我的简单的GET功能:笨查询到在REST控制器阵列错误的结果

function test_get() 
{ 
    if(!$this->get('id')) 
    { 
     $this->response(NULL, 400); 
    } 

    $query = $this->db->query('select * from test'); 
    $users = $query->result(); 

    $user = @$users[$this->get('id')]; 

    if($user) 
    { 
     $this->response($user, 200); // 200 being the HTTP response code 
    } 

    else 
    { 
     $this->response(array('error' => 'User could not be found'), 404); 
    } 
} 

它的工作原理,到目前为止,但我不知道为什么我“M获取ID 2作为结果,当我打开http://.../test/id/1

<xml><id>2</id><attribut1>Testdata</attribut1><attribut2>asdfasdf</attribut2><testcol>asf</testcol></xml> 

当我打开http://.../test/id/2我发现了该ID 3作为结果。

应该不是http://.../test/id/1 - > id 1?

回答

1

这是一个错误的问题。您正在索引$users数组(基于零),但您的ID是基于1的。当您的用户ID存在差距时,您会遇到更严重的问题(您将以随机增量关闭,而不仅仅是1次)。试试这个:

function test_get() 
{ 
    if(!$this->get('id')) 
    { 
     $this->response(NULL, 400); 
    } 

    $user = $this->db->where('id', $this->get('id'))->get('test')->first_row(); 

    if($user) 
    { 
     $this->response($user, 200); // 200 being the HTTP response code 
    } 

    else 
    { 
     $this->response(array('error' => 'User could not be found'), 404); 
    } 
} 
+0

哦,当然,数组是基于零!你的例子就是解决方案。非常感谢 :) – milepile 2012-02-29 08:51:30