2015-10-14 41 views
1

获取数据笨型号功能我用下面的函数从MySQL数据库获取数据从MySQL

从我mododel.php代码包是:

function get_all_devices($user_id = NULL) { 
    if ($user_id) { 
     $sql = " 
      SELECT * 
      FROM {$this->_db} 
      WHERE user_id = " . $this->db->escape($user_id) . " 

     "; 

     $query = $this->db->query($sql); 

     if ($query->num_rows()) { 
      return $query->row_array(); 
     } 
    } 

    return FALSE; 
} 

的DB结构的cols:id, user_id, device, value

但它只提取最后一条记录。 我如何获得数组中的所有记录。

回答

0

使用result_array()代替row_array()

function get_all_devices($user_id = NULL) { 
    if ($user_id) { 
     $sql = " 
      SELECT * 
      FROM {$this->_db} 
      WHERE user_id = " . $this->db->escape($user_id) . " 

     "; 

     $query = $this->db->query($sql); 

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

    return FALSE; 
} 

将返回所有记录。 row_array()只返回一个记录

0

好吧,我会重构代码和修改需要的地方:

function get_all_devices($user_id = NULL) { 
     if ($user_id) { 
      $this->db->where('user_id', $user_id);// you don't have to escape `$user_id` value, since `$this->db->where()` escapes it implicitly. 
      $query = $this->db->get($this->_db); //executes `select *` on table `$this->_db`, and returns.  
      //if you want to get only specific columns, use $this->db->select('col1, col2'), otherwise you don't need to specify it, since it implicitly selects everything.  
      if ($query->num_rows()) { 
       return $query->result_array();//use result_array() to retrieve the whole result instead of row_array() which retrieves only one row; 
      } 
     } 

     return FALSE; 
    }