Codeigniter資料庫操作

2022-02-06 06:58:04 字數 2843 閱讀 5958

查詢

$query = $this->db_query("select * from table");

******************************====

*///result() 返回物件陣列

$data = $query->result();

//result_array() 返回資料

$data = $query->result_array();

//row() 只返回一行物件陣列

$data = $query->row();

//num_rows() 返回查詢結果行數

$data = $query->num_rows();

//num_fields() 返回查詢請求的字段個數

$data = $query->num_fields();

//row_array() 只返回一行陣列

$data = $query->row_array();

//free_result() 釋放當前查詢所占用的記憶體並刪除關聯資源標識

$data = $query->free_result();

/*******************************====

插入操作

******************************====

*///上次插入操作生成的id

echo $this->db->insert_id();

//寫入和更新操作被影響的行數

echo $this->db->affected_rows();

//返回指定表的總行數

echo $this->db->count_all('table_name');

//輸出當前的資料庫版本號

echo $this->db->version();

//輸出當前的資料庫平台

echo $this->db->platform();

//返回最後執行的查詢語句

echo $this->db->last_query();

//插入資料,被插入的資料會被自動轉換和過濾,例如:

//$data = array('name' => $name, 'email' => $email, 'url' => $url);

$this->db->insert_string('table_name', $data);

/*******************************====

更新操作

******************************====

*///更新資料,被更新的資料會被自動轉換和過濾,例如:

//$data = array('name' => $name, 'email' => $email, 'url' => $url);

//$where = "author_id = 1 and status = 'active'";

$this->db->update_string('table_name', $data, $where);

/*******************************====

選擇資料

******************************====

*///獲取表的全部資料

$this->db->get('table_name');

//第二個引數為輸出條數,第三個引數為開始位置

$this->db->get('table_name', 10, 20);

//獲取資料,第乙個引數為表名,第二個為獲取條件,第三個為條數

$this->db->get_where('table_name', array('id'=>$id), $offset);

//select方式獲取資料

$this->db->select('title, content, date');

$data = $this->db->get('table_name');

//獲取欄位的最大值,第二個引數為別名,相當於max(age) as nianling

$this->db->select_max('age');

$this->db->select_max('age', 'nianling');

//獲取欄位的最小值

$this->db->select_min('age');

$this->db->select_min('age', 'nianling');

//獲取欄位的和

$this->db->select_sum('age');

$this->db->select_sum('age', 'nianling');

//自定義from表

$this->db->select('title', content, date');

$this->db->from('table_name');

//查詢條件 where name = 'joe' and title = 'boss' and status = 'active'

$this->db->where('name', $name);

$this->db->where('title', $title);

$this->db->where('status', $status);

//範圍查詢

$this->db->where_in('item1', 'item2');

$this->db->where_not_in('item1', 'item2');

//匹配,第三個引數為匹配模式 title like '%match%'

$this->db->like('title', 'match', 'before/after/both');

codeigniter 資料庫快取

ci預設的cache on 一旦開啟,永遠不失效,除非自己刪除。比較弱智。ci database db dirver.php 中 1021行 cache on 函式替換為 ci database db cache.php 中 90行 read 函式 if false cachedata read f...

codeigniter對資料庫的常用操作

查詢 query this db query select from table result 返回物件陣列 data query result result array 返回資料 data query result array row 只返回一行物件陣列 data query row num ro...

codeigniter自帶資料庫類使用方法說明

初始化資料庫類 依據你的資料庫配置載入並初始化資料庫類 複製 如下 this load database 被載入之後你可以在任何地方使用它。以物件形式返回查詢結果 複製 如下 query this db query select name,title,email from my table fore...