Codeigniter模型函数从mysql获取数据

时间:2015-10-14 08:12:00

标签: php mysql codeigniter

我正在使用以下函数从mysql db获取数据

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

数据库结构cols:id, user_id, device, value

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

2 个答案:

答案 0 :(得分: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()只返回一条记录

答案 1 :(得分: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;
    }