codeigniter db操作方法


  • 鏈接數據庫
  • ——-
  • $this->load->database();//手動連接數據庫
  • //連接多數據庫
  • $DB1 = $this->load->database(‘group_one’, TRUE);
  • $DB2 = $this->load->database(‘group_two’, TRUE);
  • —————————————————–
  • 查詢
  • ——-
  • //參數綁定形式
  • $sql = “SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?”;
  • $this->db->query($sql, array(3, ‘live’, ‘Rick’));
  • //多結果標准查詢
  • $query = $this->db->query($sql); //自定義
  • $query = $this->db->get(‘tablename’); //便捷形式,相當於:SELECT * FROM tablename
  • $query = $this->db->get(‘tablename’, 10, 20); // 相當於: SELECT * FROM tablename LIMIT 20, 10
  • $query->result() //對象形式
  • $query->result_array() //數組形式
  • $query->num_rows() //總條數
  • $query->num_fields() //字段數
  • //單結果標准查詢
  • $row = $query->row(); //對象形式
  • $row = $query->row_array(); //數組形式
  • —————————————————–
  • 插入
  • ——-
  • $data = array(
  • ‘title’ => $title,
  • ‘name’ => $name
  • );
  • $this->db->insert(‘tablename’, $data); //便捷插入
  • $this->db->insert_string(‘tablename’, $data);  //便捷插入
  • $this->db->insert_id() //剛插入的id
  • $this->db->affected_rows() //影響的行數(update,insert)
  • —————————————————–
  • 更新
  • ——-
  • $data = array(
  • ‘name’ => $name,
  • ‘email’ => $email
  • );
  • $where = “id = 1″;
  • $this->db->update(‘tablename’, $data);
  • $this->db->update_string(‘tablename’, $data, $where);
  • —————————————————–
  • 刪除
  • ——-
  • $array = array(
  • ‘name’ => $name,
  • ‘title’ => $title
  • );
  • $this->db->delete(‘tablename’, $array);
  • // Produces:
  • // “DELETE FROM tablename WHERE name = ‘$name’ AND title = ‘$title’”
  • $this->db->truncate(‘tablename’); //清空表
  • // Produce: TRUNCATE tablename
  • —————————————————–
  • (where)
  • ——-
  • $array = array(
  • ‘name’ => $name,
  • ‘title’ => $title
  • );
  • $this->db->where($array);
  • // Produces: “WHERE name = ‘$name’ AND title = ‘$title’”
  • —————————————————–
  • $this->db->count_all(‘tablename’); //表中記錄總行數
  • —————————————————–
  • $query->free_result() //釋放資源


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM