欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

codeigniter中DB类的用法收集

程序员文章站 2022-04-29 21:21:00
...
  1. 链接数据库

  2. -------
  3. $this->load->database();//手动连接数据库
  4. //连接多数据库
  5. $DB1 = $this->load->database('group_one', TRUE);
  6. $DB2 = $this->load->database('group_two', TRUE);
  7. 查询

  8. -------
  9. //参数绑定形式
  10. $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
  11. $this->db->query($sql, array(3, 'live', 'Rick'));
  12. //多结果标准查询
  13. $query = $this->db->query($sql); //自定义
  14. $query = $this->db->get('tablename'); //便捷形式,相当于:SELECT * FROM tablename
  15. $query = $this->db->get('tablename', 10, 20); // 相当于: SELECT * FROM tablename LIMIT 20, 10
  16. $query->result() //对象形式
  17. $query->result_array() //数组形式
  18. $query->num_rows() //总条数
  19. $query->num_fields() //字段数
  20. //单结果标准查询
  21. $row = $query->row(); //对象形式
  22. $row = $query->row_array(); //数组形式
  23. 插入
  24. -------
  25. $data = array(
  26. 'title' => $title,
  27. 'name' => $name
  28. );
  29. $this->db->insert('tablename', $data); //便捷插入
  30. $this->db->insert_string('tablename', $data); //便捷插入
  31. $this->db->insert_id() //刚插入的id
  32. $this->db->affected_rows() //影响的行数(update,insert)
  33. 更新

  34. -------
  35. $data = array(
  36. 'name' => $name,
  37. 'email' => $email
  38. );
  39. $where = "id = 1";
  40. $this->db->update('tablename', $data);
  41. $this->db->update_string('tablename', $data, $where);
  42. 删除

  43. -------
  44. $array = array(
  45. 'name' => $name,
  46. 'title' => $title
  47. );
  48. $this->db->delete('tablename', $array);
  49. // Produces:
  50. // "DELETE FROM tablename WHERE name = '$name' AND title = '$title'"
  51. $this->db->truncate('tablename'); //清空表
  52. // Produce: TRUNCATE tablename
  53. (where)

  54. -------
  55. $array = array(
  56. 'name' => $name,
  57. 'title' => $title
  58. );
  59. $this->db->where($array);
  60. // Produces: "WHERE name = '$name' AND title = '$title'"
  61. -----------------------------------------------------
  62. $this->db->count_all('tablename'); //表中记录总行数
  63. -----------------------------------------------------
  64. $query->free_result() //释放资源
复制代码