汇总CodeIgniter(CI)的数据库操作函数

分类:PHP_Python| 发布:佚名| 查看:1852 | 发表时间:2014/8/15

网上倒是有不少Codeigniter数据库操作的介绍,这里做一个汇总。

代码如下:
001//查询:
002$query = $this->db_query("SELECT * FROM table");
003 ==================================
004 
005//result() 返回对象数组
006$data = $query->result();
007 
008//result_array() 返回数据
009$data = $query->result_array();
010 
011//row() 只返回一行对象数组
012$data = $query->row();
013 
014//num_rows() 返回查询结果行数
015$data = $query->num_rows();
016 
017//num_fields() 返回查询请求的字段个数
018$data = $query->num_fields();
019 
020//row_array() 只返回一行数组
021$data = $query->row_array();
022 
023//free_result() 释放当前查询所占用的内存并删除关联资源标识
024$data = $query->free_result();
025 
026/*
027 ==================================
028 插入操作
029 ==================================
030*/
031 
032//上次插入操作生成的ID
033echo $this->db->insert_id();
034 
035//写入和更新操作被影响的行数
036echo $this->db->affected_rows();
037 
038//返回指定表的总行数
039echo $this->db->count_all('table_name');
040 
041//输出当前的数据库版本号
042echo $this->db->version();
043 
044//输出当前的数据库平台
045echo $this->db->platform();
046 
047//返回最后运行的查询语句
048echo $this->db->last_query();
049 
050//插入数据,被插入的数据会被自动转换和过滤,例如:
051//$data = array('name' => $name, 'email' => $email, 'url' => $url);
052$this->db->insert_string('table_name', $data);
053 
054/*
055 ==================================
056 更新操作
057 ==================================
058*/
059 
060//更新数据,被更新的数据会被自动转换和过滤,例如:
061//$data = array('name' => $name, 'email' => $email, 'url' => $url);
062//$where = "author_id = 1 AND status = 'active'";
063$this->db->update_string('table_name', $data, $where);
064 
065/*
066 ==================================
067 选择数据
068 ==================================
069*/
070 
071//获取表的全部数据
072$this->db->get('table_name');
073 
074//第二个参数为输出条数,第三个参数为开始位置
075$this->db->get('table_name', 10, 20);
076 
077//获取数据,第一个参数为表名,第二个为获取条件,第三个为条数
078$this->db->get_where('table_name', array('id'=>$id), $offset);
079 
080//select方式获取数据
081$this->db->select('title, content, date');
082$data = $this->db->get('table_name');
083 
084//获取字段的最大值,第二个参数为别名,相当于max(age) AS nianling
085$this->db->select_max('age');
086$this->db->select_max('age', 'nianling');
087 
088//获取字段的最小值
089$this->db->select_min('age');
090$this->db->select_min('age', 'nianling');
091 
092//获取字段的和
093$this->db->select_sum('age');
094$this->db->select_sum('age', 'nianling');
095 
096//自定义from表
097$this->db->select('title', content, date');
098$this->db->from('table_name');
099 
100//查询条件 WHERE name = 'Joe' AND title = "boss" AND status = 'active'
101$this->db->where('name', $name);
102$this->db->where('title', $title);
103$this->db->where('status', $status);
104 
105//范围查询
106$this->db->where_in('item1', 'item2');
107$this->db->where_not_in('item1', 'item2');
108 
109//匹配,第三个参数为匹配模式 title LIKE '%match%'
110$this->db->like('title', 'match', 'before/after/both');
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/php-python/1590.html