2012-11-25 22 views
6

我正在爲我正在開發的移動應用程序創建Web服務後端。 (我是一名Obj-C開發人員,而不是網頁設計師!)基本上我想使用Codeigniter和Phil Sturgeon的RESTful API服務器https://github.com/philsturgeon/codeigniter-restserver但是,我在安裝和工作時遇到了一些麻煩。使用CodeIgniter的REST API

我有設置數據的MySQL數據庫。我需要一些幫助來編寫一個CodeIgniter PHP模型和控制器,它返回數據庫內部的JSON數據。所有的教程和論壇帖子的我都找到了控制器中的硬編碼數據,而不是MySQL數據庫。我最好喜歡將URL的格式設置爲這樣的http://api.mysite.com/v1/search?id=1&name=foo&city=bar,我可能會有50多個參數在url中傳遞。

用菲爾的代碼,我想出了這個作爲我的控制器:

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

    $data = $this->grid_m->get_id($this->get('id')); 
    if ($data) 
    { 
     $this->response($data, 200); 
    } 
    else 
    { 
     $this->response(NULL, 404); 
    } 
} 

這只是讓我一個搜索詞:?ID =#。我需要知道如何讓多個搜索字詞

這是我笨型號:

<?php 

class Grid_m extends CI_Model 
{ 

function get_all() 
{ 
    $query = $this->db->get('grid'); 
    if ($query->num_rows() > 0) 
    { 
     return $query->result(); 
    } 
    return FALSE;; 
} 

這只是在我的MySQL數據庫返回一切,無論什麼ID或網址學期,我通過它的URL。

當談到開發我自己的自定義API時,我是一個很大的小菜鳥,所以關於如何解決我的控制器和數據庫模型的任何建議都將是一個巨大的幫助!

感謝您的幫助!

-Brian

+0

那麼,你的方法被稱爲「get_all」,所以我想的行爲是正確的......展現了「get_id()」方法,而不是 –

回答

0

用戶Codeigniter's Active record建造合適的查詢,可以構建任何類型的使用活動記錄的方法查詢,請參考下面的例子我剛纔在裏面加一個條件,你可以根據自己的需要添加更多的條件。

<?php 
class Grid_m extends CI_Model 
{  
    function get_all() 
    { 
    $this->db->select('col1, col2, col3')->where('id', 5); 
    $query = $this->db->get('grid'); 

    if ($query->num_rows() > 0) 
    { 
     return $query->result(); 
    } 
    return FALSE;; 
    } 

} 
+2

中的代碼片斷,他的真正使用它已經 –

+0

但他是不知道其他方法來查詢 –

+0

這是偉大的,幫助我完成我的問題的一部分,但我怎麼可以從我的URL傳遞更多的參數?即:搜索?類型=餐廳和位置=聖%20Francicso – Brian

0

請檢查您查詢

$query = $this->db->get_where('grid', array('id' => $id)); 
1

這是老問題,但如果有人到這裏,仍然需要幫助,請嘗試以下代碼:

在你的控制器:

public function index_get() 
{ 
    $where = ''; 

    if ($this->get('id')) // search by id when id passed by 
    {    
     $where .= 'id = '.$this->get('id'); 
    } 

    if ($this->get('name')) // add search by name when name passed by   
    { 
     $where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'"; 
    } 

    if ($this->get('city')) // add search by city when city passed by 
    { 
     $where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'"; 
    } 

    // you can add as many as search terms 

    if (! empty($where)) 
    { 
     $data = $this->grid_m->get_searched($where); 

     if ($data) 
     { 
      $this->response($data, 200); 
     } 
     else 
     { 
      $this->response(NULL, 404); 
     } 
    } 
    else 
    { 
     $this->response(NULL, 404); 
    } 
} 

在您的模型中,創建get_searched功能:

class Grid_m extends CI_Model 
{ 
    function get_searched($where = NULL) 
    { 
     if (! is_null($where)) 
     { 
      $this->db->where($where); 
      $query = $this->db->get('grid'); 

      if ($query->num_rows() > 0) 
      { 
       return $query->result(); 
      } 
     } 
     return FALSE; 
    } 
}