2016-10-21 74 views
0

我已經學習了CodeIgniter,但是我在將純php查詢轉換爲查詢CodeIgniter時遇到困難,如何在CodeIgniter中修復我的查詢?從純php查詢CodeIgniter

這個查詢使用笨

public function get_kal($id) { 
    $query = $this->db 
      ->select('myname as name') 
      ->from('mytable') 
      ->where('myname', $id) 
      ->like('%%%s%%') 
      ->order_by('myname','ASC'); 
      ->get("q"); 

    $arr = array(); 

    $rs = mysql_query($query); 

    while($obj = mysql_fetch_object($rs)) 
    { 
     $arr[] = $obj; 
    } 

    echo json_encode($arr);  
} 

該查詢與純PHP

public function get_name($id) { 
     $query = sprintf("SELECT myname as name from mytable WHERE myname LIKE '%%%s%%' ORDER BY myname DESC ", mysql_real_escape_string($_GET["q"])); 
     $arr = array(); 
     $rs = mysql_query($query); 

     while($obj = mysql_fetch_object($rs)) 
     { 
      $arr[] = $obj; 
     } 

     echo json_encode($arr); 
    } 

回答

0
$query = $this->db->query($SQL); 
echo json_encode($query->result_array()); 
1

您可以直接查詢使用

$this->db->query('YOUR QUERY HERE'); 

,你也可以建立查詢

$query = $this->db 
      ->select('myname as name') 
      ->from('mytable') 
      ->like('myname', $this->input->get('q', TRUE)) 
      ->order_by('myname','ASC'); 

這裏是Official Doc

0

您可以在下面的格式也使用由。
1.多個結果
2.單結果

1. $q = $this->db->query('MYSQL QUERY'); 
echo json_encode($q->result_array()); 


2.$q = $this->db->query('MYSQL QUERY'); 
echo json_encode($q->row_array());