Codeigniter模型函数从mysql获取数据


Codeigniter Model function get data from 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

但是它只提取最后一条记录。我怎么能得到所有的记录在一个数组

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()只返回一条记录

好的,我将重构代码并在需要的地方进行修改:

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;
    }