1.数据库配置
数据库配置文件路径application/config/database.php
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
2.连接数据库
自动连接:在每一个页面加载时自动实例化数据库类。
要启用“自动连接”, 可在 application/config/autoload.php 中的 library 数组里添加 database:
$autoload['libraries'] = array('database');
手动连接:如果你只有一部分页面需要数据库连接,你可以在那些有需要的函数里手工添加
如下代码来连接数据库,或者写在类的构造函数里,让整个类都可以访问:
$this->load->database();
3.查询
//插入数据,被插入的数据会被自动转换和过滤,例如:
$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);
//select
$this->db->select('title, content, date');
$this->db->select_min('age');//获取字段的最小值
$this->db->select_sum('age', 'nianling');//获取字段的最大值,第二个参数为别名,相当于max(age) AS nianling
//from
$this->db->from('table_name');
//where
$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status);
//join
$this->db->join('prize_setting as p', 'w.pk_prize_id = p.pk_prize_id', 'inner');
//where_in
$this->db->where_in('item1', 'item2');
//where_not_in
$this->db->where_not_in('item1', 'item2');
//like,第三个参数为匹配模式 title LIKE '%match%'
$this->db->like('title', 'match', 'before/after/both');
//not_like
$this->db->not_like();
//group by
$this->db->group_by('title', 'date');
//order by
$this->db->order_by('title', 'desc');
//限制条数,参数1为取的数据条数为10,参数2为第20条开始
$this->db->limit(10, 20);
//获取表的全部数据
$this->db->get();
$this->db->get('table_name');
//第二个参数为输出条数,第三个参数为开始位置
$this->db->get('table_name', 10, 20);
//获取数据,第一个参数为表名,第二个为获取条件,第三个为条数
$this->db->get_where('table_name', array('id'=>$id), $offset);
//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();
4.查询辅助方法
//返回最后运行的查询语句
echo $this->db->last_query();
//上次插入操作生成的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();