用codeigniter也有一段时间了,一直没有做什么总结。现在总结一些Codeigniter操作数据库表的优化写法,虽说不全,但是也确实可以帮助那些刚刚上手CI的同学。
链接数据库
1 | $this ->load->database(); //手动连接数据库 |
2 | //连接多数据库 |
3 | $DB1 = $this ->load->database( 'group_one' , TRUE); |
4 | $DB2 = $this ->load->database( 'group_two' , TRUE); |
查询
01 | //参数绑定形式 |
02 | $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?" ; |
03 | $this ->db->query( $sql , array (3, 'live' , 'Rick' )); |
04 |
05 | //多结果标准查询 |
06 | $query = $this ->db->query( $sql ); //自定义 |
07 | $query = $this ->db->get( 'tablename' ); //便捷形式,相当于:SELECT * FROM tablename |
08 | $query = $this ->db->get( 'tablename' , 10, 20); // 相当于: SELECT * FROM tablename LIMIT 20, 10 |
09 |
10 | $query ->result() //对象形式 |
11 | $query ->result_array() //数组形式 |
12 | /* |
13 | foreach ($query->result() as $row) |
14 | { |
15 | echo $row->title; |
16 | echo $row->name; |
17 | echo $row->email; |
18 | } |
19 | */ |
20 | $query ->num_rows() //总条数 |
21 | $query ->num_fields() //字段数 |
22 |
23 | //单结果标准查询 camnpr |
24 | $row = $query ->row(); //对象形式 |
25 | $row = $query ->row_array(); //数组形式 |
26 | /* |
27 | $row = $query->row_array(); |
28 | echo $row['name']; |
29 | */ |
30 | |
插入
1 | $data = array ( |
2 | 'title' => $title , |
3 | 'name' => $name |
4 | ); |
5 | $this ->db->insert( 'tablename' , $data ); //便捷插入 |
6 | $this ->db->insert_string( 'tablename' , $data ); //便捷插入 |
7 |
8 | $this ->db->insert_id() //刚插入的id |
9 | $this ->db->affected_rows() //影响的行数(update,insert) |
更新
1 | $data = array ( |
2 | 'name' => $name , |
3 | 'email' => $email |
4 | ); |
5 | $where = "id = 1" ; |
6 | $this ->db->update( 'tablename' , $data ); |
7 | $this ->db->update_string( 'tablename' , $data , $where ); |
删除
01 | $array = array ( |
02 | 'name' => $name , |
03 | 'title' => $title |
04 | ); |
05 | $this ->db-> delete ( 'tablename' , $array ); |
06 |
07 | // Produces: |
08 | // "DELETE FROM tablename WHERE name = '$name' AND title = "$title"" |
09 |
10 | $this ->db->truncate( 'tablename' ); //清空表 |
11 | // Produce: TRUNCATE tablename |
12 |
13 | |
14 |
15 | ----------------------------------------------------- |
16 | (where) |
17 | ------- |
18 |
19 | $array = array ( |
20 | 'name' => $name , |
21 | 'title' => $title |
22 | ); |
23 | $this ->db->where( $array ); |
24 | // Produces: "WHERE name = '$name' AND title = "$title"" |
25 | ----------------------------------------------------- |
26 | $this ->db->count_all( 'tablename' ); //表中记录总行数 camnpr |
27 | ----------------------------------------------------- |
28 | $query ->free_result() //释放资源 |