PHP/CI Model2019. 1. 14. 15:13

CodeIgniter 의 모델 콤포넌트에서 DB 다루기



application/config/database.php 에서 데이터베이스 정보 입력

$db['default'] = array(

'dsn' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'sample_db',

'dbdriver' => 'mysqli',

        .........



Model  생성자 안에서 DB 초기화

$this->load->database();



데이터베이스 자동 연결

혹은 application/config/database.php에 자동로드 설정하면 위의 코드는 필요 없다

$autoload['libraries'] = array('database', 'session');



다수개의 행을 가져와서 배열로 변환

$result = $this->db->get('테이블명');

$data['rows'] = $result->result_array(); //각행이 연관배열로 표현된 2차원 배열 리턴

$data['title'] = 'Members List';



한행을 검색하여 가져오기

$result = $this->db->get_where('테이블명', array('id'=>11));

//위의 문장은 아래처럼 2개문장으로 표현할 수 있다

$this->db->where('id', 11);

$result = $this->db->get('테이블명');

$data = $result->row_array(); // 한행을 연관배열로 리턴, NULL



get_where() 함수

get_where([$table = ''[, $where = NULL[, $limit = NULL[, $offset = NULL]]]])

Parameters:

$table (mixed) – The table(s) to fetch data from; string or array

$where (string) – The WHERE clause

$limit (int) – The LIMIT clause

$offset (int) – The OFFSET clause



웹브라우저 파라미터를 추출하여 DB에 저장하기

$this->load->helper('url');

$title = $this->input->post('title');

$content = $this->input->post('content');

$data = array(

'title'=>$title,

'content'=>$content

);

$this->db->insert('테이블명', $data); //성공시 TRUE, 실패시 FALSE



특정 행의 컬럼 값을 변경하기

$data = array(

'title'=>$title,

'content'=>$content

);

$this->db->where('id', $id);

$this->db->update('테이블명', $data);  //성공시 TRUE, 실패시 FALSE

$this->db->update('테이블명', $data, $where);



특정 행 삭제

$this->db->where('id', $id);

$this->db->delete('테이블명'); // 실패시 FALSE

$this->db->delete('테이블명', $where);



SQL 문장을 직접 사용할 때

$this->db->query($sql); 

$this->db->query($sql, sql문장에 전달될 파라미터배열);


//$sql이 read type(SELECT)이라면 결과값 리턴

//$sql이 write type(INSERT,UPDATE,DELETE)이라면 TRUE|FALSE 리턴




Posted by cwisky