쿼리 빌더 클래스
코드이그나이터는 Query Builder 클래스에 대한 액세스를 제공합니다.
이 패턴은 최소한의 스크립팅으로 데이터베이스에서 정보를 검색, 삽입 및 업데이트할 수 있게 합니다.
어떤 경우에는 데이터베이스 작업을 수행하는 데 한 줄 또는 두 줄만의 코드로 가능합니다.
코드이그나이터는 각 데이터베이스 테이블마다 자체적인 클래스 파일을 요구하지 않습니다.
대신에 더 단순한 인터페이스를 공급합니다.
단순성 이외에도 쿼리 빌더를 사용하면 데이터베이스에서 독립된 응용 프로그램을 만들 수 있다는 이점이 있습니다.
이는 쿼리 구문이 각 데이터베이스마다의 어댑터에서 생성되므로 가능합니다.
또한 값이 시스템에 의해 자동으로 이스케이프되므로 더 안전한 쿼리가 가능합니다.
주의사항
자신만의 쿼리를 작성하려 하는 경우, 데이터베이스 설정 파일에서 이 클래스를 비활성화할 수 있습니다.
이렇게 하면, 핵심 데이터베이스 라이브러리 및 어댑터가 더 적은 자원을 사용하도록 해 줍니다.
데이터 조회
다음 함수를 사용하면 SQL SELECT 문을 작성할 수 있습니다.
$this->db->get() 메소드
선택된 쿼리를 실행하고 결과를 반환합니다.
테이블의 모든 레코드를 검색하는 데 사용될 수 있습니다 :
$query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable
두 번째 및 세 번째 매개 변수를 사용하면 "limit" 및 "offset"을 설정할 수 있습니다 :
$query = $this->db->get('mytable', 10, 20);
// Executes: SELECT * FROM mytable LIMIT 20, 10
// (in MySQL. Other databases have slightly different syntax)
위의 함수에서 "$query"라는 변수에 값을 할당하였음을 아실 수 있습니다.
이 변수를 통해 결과값을 보여줄 수 있습니다 :
$query = $this->db->get('mytable');
foreach ($query->result() as $row)
{
echo $row->title;
}
결과물 생성과 관련된 전체 문서를 보려면 결과물 함수 관련 페이지("https://codeigniter.com/user_guide/database/results.html")를 참조하세요.
$this->db->get_compiled_select() 메소드
$this->db->get() 메소드처럼 선택 쿼리를 컴파일하지만 해당 쿼리를 실행하지는 않습니다.
이 메소드는 단순히 SQL 쿼리를 문자열로 반환합니다.
예시 :
$sql = $this->db->get_compiled_select('mytable');
echo $sql;
// Prints string: SELECT * FROM mytable
두 번째 매개 변수를 사용하면 쿼리 빌더가 쿼리를 재설정할 지 여부를 결정할 수 있습니다
(디폴트는 $this->db->get()을 사용할 때와 마찬가지로 재설정되는 것입니다) :
echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);
// 출력 문자열: SELECT * FROM mytable LIMIT 20, 10
// (MySQL의 경우 문자열로, 다른 데이터베이스의 구문은 이와 약간 다릅니다.)
echo $this->db->select('title, content, date')->get_compiled_select();
//// 출력 문자열: SELECT title, content, date FROM mytable LIMIT 20, 10
위의 예에서 주목할 점은 두 번째 쿼리가 "$this->db->from()"을 사용하지 않고 첫 번째 매개 변수에 테이블 이름을 전달하지 않았다는 점입니다.
이러한 결과가 발생한 이유는 "$this->db->reset_query()"를 사용하여 쿼리를 직접 재설정하거나 그렇게 작동하게 만드는 "$this->db->get()"을 사용하지 않았기 때문입니다.
$this->db->get_where() 메소드
db->where() 함수를 사용하는 대신, 두 번째 매개 변수에 "where"절을 추가할 수 있게 해줍니다.
이 점을 제외하고는 위의 함수와 동일합니다 :
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
where 함수에 대한 더 자세한 내용은 아래 내용을 참조하세요.
주의사항
get_where()는 이전에 getwhere()로 알려져 있었지마, 해당 메소드는 제거되었습니다.
$this->db->select() 메소드
쿼리의 SELECT 구문 일부분을 작성할 수 있게 해 줍니다 :
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
// 실행: SELECT title, content, date FROM mytable
주의사항
테이블에서 모두(*)를 선택하려 한다면, 기능을 사용할 필요가 없습니다.
매개 변수를 생략하면 코드이그나이터는 모든 필드를 선택하길 원한다고 판단하여 자동으로 'SELECT *'를 추가합니다.
$this->db->select()는 선택 사항인 두번째 매개 변수를 허용합니다.
해당 값을 "FALSE"로 설정하면 코드이그나이터는 필드 또는 테이블 이름을 보호하지 않습니다.
필드를 자동으로 이스케이프 처리하면 명령문이 손상될 수 있는 복합 select 문일 경우, 이 기능이 도움이 됩니다.
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4) AS amount_paid', FALSE);
$query = $this->db->get('mytable');
$this->db->select_max() 메소드
쿼리에 SELECT MAX (필드) 부분을 작성합니다.
결과 필드의 이름을 바꾸기 위해, 선택 사항인 두 번째 매개 변수를 포함시킬 수 있습니다
$this->db->select_max('age');
$query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members
$this->db->select_max('age', 'member_age');
$query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members
$this->db->select_min() 메소드
쿼리에 "SELECT MIN (필드)" 부분을 작성합니다.
"select_max()"와 마찬가지로 선택사항인 두 번째 매개 변수를 포함시켜 결과 필드의 이름을 바꿀 수 있습니다.
$this->db->select_min('age');
$query = $this->db->get('members'); // Produces: SELECT MIN(age) as age FROM members
$this->db->select_avg()
쿼리에 "SELECT AVG(필드)" 부분을 작성합니다.
"select_max()"와 마찬가지로 선택사항인 두 번째 매개 변수를 포함시켜 결과 필드의 이름을 바꿀 수 있습니다.
$this->db->select_avg('age');
$query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
$this->db->select_sum()
쿼리에 "SELECT SUM(필드)" 부분을 작성합니다.
"select_max()"와 마찬가지로 선택사항인 두 번째 매개 변수를 포함시켜 결과 필드의 이름을 바꿀 수 있습니다.
$this->db->select_sum('age');
$query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members
$this->db->from()
당신의 쿼리의 FROM 부분을 쓸 수 있게 해줍니다 :
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get(); // Produces: SELECT title, content, date FROM mytable
주의사항
앞서 설명한 쿼리의 FROM 부분을 "$this->db->get()" 함수에서도 지정할 수 있으므로 선호하는 방법을 선택하세요.
$this->db->join()
당신의 쿼리의 JOIN 부분을 쓸 수 있게 해줍니다 :
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
한 쿼리에서 여러 개의 조인이 필요한 경우 여러 개의 함수 호출하여 작성할 수 있습니다.
특정 유형의 JOIN이 필요하면 함수의 세 번째 매개 변수를 통해 그것을 지정할 수 있습니다.
해당 옵션: left, right, outer, inner, left outer, 및 right outer.
$this->db->join('comments', 'comments.id = blogs.id', 'left');
// Produces: LEFT JOIN comments ON comments.id = blogs.id
특정 데이터 찾기
$this->db->where()
이 함수는 네 가지 방법 중 하나를 사용하여 WHERE 절을 설정할 수 있게 해줍니다 :
주의사항
이 함수에 전달된 모든 값은 자동으로 이스케이프되므로 안전한 쿼리가 생성됩니다.
1. 간단한 key/value 방법:
$this->db->where('name', $name); // Produces: WHERE name = 'Joe'
등호 방식이 추가되었습니다.
멀티 함수 호출을 통해, 당신은 여러 값들을 연결시킬 수 있습니다 :
$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status);
// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
2. 사용자정의 key/value 방법:
비교 작업을 위해 첫 번째 매개 변수에 연산자를 포함시킬 수 있습니다 :
$this->db->where('name !=', $name);
$this->db->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
3. 연관 배열 방법:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
이 방법을 사용하여 자신의 연산자를 포함시킬 수도 있습니다 :
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);
4. 사용자 정의 문자열:
수동으로 직접 절을 작성할 수 있습니다.
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
"$this->db->where()"는 선택사항인 세 번째 매개 변수를 허용합니다.
"FALSE"로 설정하면, CodeIgniter는 필드 또는 테이블 이름을 보호하지 않습니다.
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
$this->db->or_where()
이 함수는 멀티 인스턴스가 "OR"로 조인된다는 점을 제외하고는 위 함수와 동일합니다 :
$this->db->where('name !=', $name);
$this->db->or_where('id >', $id); // Produces: WHERE name != 'Joe' OR id > 50
주의사항
"or_where()"는 이전에 "orwhere()"로 알려져 있었으나 해당 메소드는 제거되었습니다.
$this->db->where_in()
적절한 경우 SQL 쿼리에 "AND" 형태로 결합된 "WHERE IN('item', 'item')" 필드를 생성합니다.
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
$this->db->or_where_in()
적절한 경우 SQL 쿼리에 "OR" 형태로 결합된 "WHERE IN('item', 'item')" 필드를 생성합니다.
$names = array('Frank', 'Todd', 'James');
$this->db->or_where_in('username', $names);
// Produces: OR username IN ('Frank', 'Todd', 'James')
$this->db->where_not_in()
적절한 경우 SQL 쿼리에 "AND" 형태로 결합된 "WHERE NOT IN('item', 'item')" 필드를 생성합니다.
$names = array('Frank', 'Todd', 'James');
$this->db->where_not_in('username', $names);
// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')
$this->db->or_where_not_in()
적절한 경우 SQL 쿼리에 "OR" 형태로 결합된 "WHERE NOT IN('item', 'item')" 필드를 생성합니다.
$names = array('Frank', 'Todd', 'James');
$this->db->or_where_not_in('username', $names);
// Produces: OR username NOT IN ('Frank', 'Todd', 'James')
유사 데이터 찾기
$this->db->like()
이 메소드는 검색을 수행하는 데 유용한 LIKE 절을 생성하게 해 줍니다.
주의사항
이 메소드로 전달된 모든 값은 자동으로 이스케이프됩니다.
1. 간단한 key/value 방법:
$this->db->like('title', 'match');
// Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
멀티 함수 호출을 통해, 당신은 여러 값들을 "AND"로 연결시킬 수 있습니다 :
$this->db->like('title', 'match');
$this->db->like('body', 'match');
// WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
와일드 카드(%)가 있는 부분을 제어하려면, 선택사항인 세 번째 매개 변수를 사용할 수 있습니다.
옵션 값은 'before', 'after' 및 'both'(기본값)입니다.
$this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
$this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
$this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
2. 연관 배열 방법:
$array = array('title' => $match, 'page1' => $match, 'page2' => $match);
$this->db->like($array);
// WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
$this->db->or_like()
이 메소드는 멀티 인스턴스가 "OR"로 결합된다는 점을 제외하고는 위 메소드와 동일합니다:
$this->db->like('title', 'match'); $this->db->or_like('body', $match);
// WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
주의사항
"or_like()"는 이전에 "orlike()"로 알려져 있었으나 해당 메소드는 제거되었습니다.
$this->db->not_like()
이 메소드는 "NOT LIKE" 문을 생성한다는 점을 제외하고는 "like()"와 동일합니다:
$this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
$this->db->or_not_like()
이 메소드는 멀티 인스턴스가 "OR"로 결합된다는 점을 제외하고는 "not_like()"와 동일합니다:
$this->db->like('title', 'match');
$this->db->or_not_like('body', 'match');
// WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
$this->db->group_by()
쿼리의 GROUP BY 부분을 쓸 수 있게 해줍니다:
$this->db->group_by("title"); // Produces: GROUP BY title
멀티 값으로 된 배열을 전달할 수도 있습니다:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
주의사항
"group_by()"는 이전에 "groupby()"로 알려져 있었으나 해당 메소드는 제거되었습니다.
$this->db->distinct()
쿼리에 DISTINCT 키워드를 추가합니다.
$this->db->distinct();
$this->db->get('table'); // Produces: SELECT DISTINCT * FROM table
$this->db->having()
쿼리에 "HAVING" 부분을 쓸 수 있게 해줍니다.
가능한 구문은 2개로 하나 또는 두개의 인자를 사용하는 것입니다:
$this->db->having('user_id = 45'); // Produces: HAVING user_id = 45
$this->db->having('user_id', 45); // Produces: HAVING user_id = 45
멀티 값으로 된 배열을 전달할 수도 있습니다:
$this->db->having(array('title =' => 'My Title', 'id <' => $id));
// Produces: HAVING title = 'My Title', id < 45
"CodeIgniter"가 쿼리를 이스케이프 처리하는 데이터베이스를 사용하는 경우, 선택사항인 세 번째 매개 변수를 FALSE로 설정하여 이스케이프 처리를 막을 수 있습니다.
$this->db->having('user_id', 45); // Produces: HAVING `user_id` = 45 <- MySQL과 같은 데이터베이스의 경우
$this->db->having('user_id', 45, FALSE); // Produces: HAVING user_id = 45
$this->db->or_having()
"having()"과 동일하며, 단 멀티 절을 "OR"로 구분합니다:
결과값 정렬
$this->db->order_by()
"ORDER BY" 절을 설정하게 해 줍니다.
첫 번째 매개 변수는 정렬하고자 하는 컬럼명입니다.
두 번째 매개 변수는 결과값에서의 방향값입니다.
해당 옵션 값은 ASC, DESC 및 RANDOM입니다.
$this->db->order_by('title', 'DESC');
// Produces: ORDER BY `title` DESC
또는 첫 번째 매개 변수에 직접 작성한 문자열을 넣을 수도 있습니다:
$this->db->order_by('title DESC, name ASC');
// Produces: ORDER BY `title` DESC, `name` ASC
또는 멀티 함수 호출을 통해, 필요한 멀티 필드를 만들수도 있습니다.
$this->db->order_by('title', 'DESC');
$this->db->order_by('name', 'ASC');
// Produces: ORDER BY `title` DESC, `name` ASC
RANDOM 방향 옵션을 선택하면, 숫자 시드 값을 지정하지 않은 경우, 첫 번째 매개 변수가 무시됩니다.
$this->db->order_by('title', 'RANDOM');
// Produces: ORDER BY RAND()
$this->db->order_by(42, 'RANDOM');
// Produces: ORDER BY RAND(42)
주의사항
"order_by()"는 이전에 "orderby()"로 알려져 있었으나 해당 메소드는 제거되었습니다.
주의사항
랜덤 정렬 순서 지정은 현재 Oracle에서 지원되지 않으며, 대신 "ASC"로 기본 설정됩니다.
결과값 총 갯수 또는 Limiting 처리
$this->db->limit()
쿼리에서 반환하고자 하는 행 수를 제한할 수 있습니다:
$this->db->limit(10); // Produces: LIMIT 10
두 번째 매개 변수를 사용하면 결과 오프셋을 설정할 수 있습니다.
$this->db->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
$this->db->count_all_results()
활성 레코드 행 수를 결정할 수 있습니다.
쿼리는 where(), or_where(), like(), or_like() 등과 같은 쿼리 빌더 제한자를 허용합니다.
예 :
echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
$this->db->like('title', 'match');
$this->db->from('my_table');
echo $this->db->count_all_results(); // Produces an integer, like 17
이 메소드는 select()에 전달한 모든 필드 값을 재설정합니다.
필드 값들을 그대로 두려면, 두 번째 매개 변수를 FALSE로 전달하세요 :
echo $this->db->count_all_results('my_table', FALSE);
$this->db->count_all()
특정 테이블의 행 수를 결정할 수 있습니다.
첫 번째 매개 변수에 테이블 이름을 넣으세요.
예:
echo $this->db->count_all('my_table'); // Produces an integer, like 25
쿼리 group 처리
쿼리 "group"을 사용하면 WHERE 절을 괄호로 묶어 그룹을 만들 수 있습니다.
이렇게 하면 복잡한 WHERE 절이 포함된 쿼리를 만들 수 있습니다. 그리고 중첩 "group"이 지원됩니다.
예 :
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
주의사항
groups need to be balanced, make sure every group_start() is matched by a group_end().
"group"은 잘 구성되어야 합니다. 모든 "group_start()"는 "group_end()"와 매치되어야 합니다.
$this->db->group_start()
쿼리의 WHERE 절에 시작 괄호를 추가하여 새 그룹을 시작합니다.
$this->db->or_group_start()
쿼리의 WHERE 절에 시작 괄호를 추가하여 새 그룹을 시작하되, 'OR' 접두어를 사용하여 그렇게 합니다.
$this->db->not_group_start()
쿼리의 WHERE 절에 시작 괄호를 추가하여 새 그룹을 시작하되 'NOT' 접두어를 사용하여 그렇게 합니다.
$this->db->or_not_group_start()
쿼리의 WHERE 절에 시작 괄호를 추가하여 새 그룹을 시작하되 'OR NOT' 접두어를 사용하여 그렇게 합니다.
$this->db->group_end()
쿼리의 WHERE 절에 마침 괄호를 추가하여 현재 그룹을 마칩니다.
데이터 추가
$this->db->insert()
제공 데이터를 기반으로 insert 문자열을 생성하고 해당 쿼리를 실행합니다.
이 함수에 배열이나 객체를 전달할 수 있습니다.
다음은 배열을 사용하는 예입니다 :
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
첫 번째 인자는 테이블명, 두 번째 인자는 연관 배열입니다.
다음은 객체를 사용하는 예입니다 :
/*
class Myclass {
public $title = 'My Title';
public $content = 'My Content';
public $date = 'My Date';
}
*/
$object = new Myclass;
$this->db->insert('mytable', $object);
// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
첫 번째 인자는 테이블명, 두 번째 인자는 객체입니다.
주의사항
모든 값은 자동으로 이스케이프되어 안전한 쿼리를 생성합니다.
$this->db->get_compiled_insert()
"$this->db->insert()" 메소드처럼 insert 쿼리를 컴파일하지만 해당 쿼리를 실행하지는 않습니다.
이 메소드는 단순히 SQL 쿼리를 문자열로 반환합니다.
예 :
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$sql = $this->db->set($data)->get_compiled_insert('mytable');
echo $sql;
// Produces string: INSERT INTO mytable (`title`, `name`, `date`) VALUES ('My title', 'My name', 'My date')
두 번째 인자는 쿼리 작성기의 쿼리를 재설정할지 여부를 설정합니다. (기본값은 $this->db->insert() 메소드 상태와 같습니다)
echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);
// Produces string: INSERT INTO mytable (`title`) VALUES ('My Title')
echo $this->db->set('content', 'My Content')->get_compiled_insert();
// Produces string: INSERT INTO mytable (`title`, `content`) VALUES ('My Title', 'My Content')
위의 예에서 주목할 점은 두 번째 쿼리가 "$this->db->from()" 메소드를 이용하지 않는다는 점입니다. 그리고, 첫 번째 매개 변수에 테이블 이름을 전달하지도 않습니다.
그 이유는 해당 쿼리가 값을 재설정하거나 "$this->db->reset_query()"로 직접 재설정하는 "$this->db->insert()" 메소드를 사용하지 않기 때문입니다.
주의사항
이 메소드는 배치 insert 작업을 위해 사용할 수 없습니다.
$this->db->insert_batch()
제공 데이터를 기반으로 insert 문자열을 생성합니다. 그리고 해당 쿼리를 실행합니다.
함수에 배열이나 객체를 전달할 수 있습니다.
다음은 배열을 사용하는 예입니다 :
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
첫 번째 인자는 테이블명, 두 번째 인자는 연관 배열입니다.
주의사항
모든 값은 자동으로 이스케이프되어 안전한 쿼리를 생성합니다.
데이터 업데이트
$this->db->replace()
이 메소드는 PRIMARY 및 UNIQUE 키를 결정 요인으로 사용하여 SQL 표준 "DELETE + INSERT"(선택사항)을 사용하는 REPLACE 문을 실행합니다.
select(), update(), delete() 및 insert() 메소드를 조합시키는 복잡한 로직 구현의 어려움을 줄일 수 있습니다.
예 :
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->replace('table', $data);
// Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
위 예에서 title 필드가 "primary key"라고 가정할 경우, title 값이 'My title' 인 행이 삭제된 후, 새로운 행으로 대체됩니다.
"insert()" 메소드와 마찬가지로 "set()" 메소드를 사용할 수 있습니다. 그리고 모든 필드는 자동으로 이스케이프됩니다.
$this->db->set()
이 함수는 insert 또는 update 값을 설정하도록 해 줍니다.
데이터 배열을 직접 "insert" 또는 "update" 함수에 전달하는 대신 이 함수를 사용할 수 있습니다 :
$this->db->set('name', $name);
$this->db->insert('mytable'); // Produces: INSERT INTO mytable (`name`) VALUES ('{$name}')
멀티 함수를 호출하는 경우, "insert" 또는 "update" 수행 여부에 기반하여 조립될 것입니다 :
$this->db->set('name', $name);
$this->db->set('title', $title);
$this->db->set('status', $status);
$this->db->insert('mytable');
set()은 선택 사항으로 세 번째 인자($escape)를 허용합니다. 이 인자를 "FALSE"로 설정하면 데이터가 이스케이스되지 않도록 막아줍니다.
차이점을 설명하기 위해, 이스케이프(escape) 인자를 사용한 예와 사용하지 않은 set() 메소드 예제를 수록합니다 :
$this->db->set('field', 'field+1', FALSE);
$this->db->where('id', 2);
$this->db->update('mytable'); // gives UPDATE mytable SET field = field+1 WHERE id = 2
$this->db->set('field', 'field+1');
$this->db->where('id', 2);
$this->db->update('mytable'); // gives UPDATE `mytable` SET `field` = 'field+1' WHERE `id` = 2
또한 이 함수에 연관 배열을 넣을 수도 있습니다 :
$array = array(
'name' => $name,
'title' => $title,
'status' => $status
);
$this->db->set($array);
$this->db->insert('mytable');
그리고, 객체 또한 가능합니다 :
/*
class Myclass {
public $title = 'My Title';
public $content = 'My Content';
public $date = 'My Date';
}
*/
$object = new Myclass;
$this->db->set($object);
$this->db->insert('mytable');
$this->db->update()
제공 데이터를 기반으로 update 문자열을 생성합니다. 그리고 해당 쿼리를 실행합니다.
함수에 배열이나 객체를 전달할 수 있습니다.
다음은 배열을 사용하는 예입니다 :
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
// Produces:
//
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id
그리고, 객체를 사용할 수도 있습니다 :
/*
class Myclass {
public $title = 'My Title';
public $content = 'My Content';
public $date = 'My Date';
}
*/
$object = new Myclass;
$this->db->where('id', $id);
$this->db->update('mytable', $object);
// Produces:
//
// UPDATE `mytable`
// SET `title` = '{$title}', `name` = '{$name}', `date` = '{$date}'
// WHERE id = `$id`
주의사항
모든 값은 자동으로 이스케이프되어 안전한 쿼리를 생성합니다.
"$this->db->where()" 함수를 사용하여 WHERE절 사용을 선언할 수 있습니다.
선택 사항으로, 이 정보를 update 함수에 문자열로 직접 전달할 수 있습니다 :
$this->db->update('mytable', $data, "id = 4");
또는 배열로 그렇게 할 수 있습니다 :
$this->db->update('mytable', $data, array('id' => $id));
또한 위에서 설명한 "$this->db->set()" 함수를 사용하여 업데이트를 수행할 수도 있습니다.
$this->db->update_batch()
제공 데이터를 기반으로 update 문자열을 생성합니다. 그리고 해당 쿼리를 실행합니다.
함수에 배열이나 객체를 전달할 수 있습니다.
다음은 배열을 사용하는 예입니다 :
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
// Produces:
// UPDATE `mytable` SET `name` = CASE
// WHEN `title` = 'My title' THEN 'My Name 2'
// WHEN `title` = 'Another title' THEN 'Another Name 2'
// ELSE `name` END,
// `date` = CASE
// WHEN `title` = 'My title' THEN 'My date 2'
// WHEN `title` = 'Another title' THEN 'Another date 2'
// ELSE `date` END
// WHERE `title` IN ('My title','Another title')
첫 번째 인자는 테이블명, 두 번째 인자는 연관 배열입니다. 그리고 세 번째 인자는 "where" 키입니다.
주의사항
모든 값은 자동으로 이스케이프되어 안전한 쿼리를 생성합니다.
주의사항
"affected_rows()" 메소드는 본질적인 작동 방식 때문에 원하는 적절한 결과를 제공받지 못합니다.
대신, "update_batch()" 메소드는 영향을 받은 행 수를 반환합니다.
$this->db->get_compiled_update()
이 작업은 INSERT SQL 문자열 대신 UPDATE SQL 문자열을 생성한다는 점을 제외하면, "$this->db->get_compiled_insert()" 메소드와 똑같은 방식으로 작동됩니다.
더 자세한 내용은 "$this->db->get_compiled_insert()" 내용을 참조하세요.
주의사항
이 메소드는 배치 update 작업을 위해 사용할 수 없습니다.
데이터 삭제
$this->db->delete()
delete SQL 문자열을 생성하고 해당 쿼리를 실행합니다.
$this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
첫 번째 인자는 테이블명, 두 번째 인자는 where 절입니다.
그리고 두 번째 인자에 데이터를 넣는 대신 "where()" 또는 "or_where()" 메소드를 사용할 수도 있습니다 :
$this->db->where('id', $id);
$this->db->delete('mytable');
// Produces:
// DELETE FROM mytable
// WHERE id = $id
하나 이상의 테이블 데이터를 삭제하려면 테이블 이름으로 구성된 배열을 "delete()" 메소드에 전달할 수 있습니다.
$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);
특정 테이블의 모든 데이터를 삭제하려면 "truncate()" 함수 또는 "empty_table()"을 사용할 수 있습니다.
$this->db->empty_table()
delete SQL 문자열을 생성하고 해당 쿼리를 실행합니다 :
$this->db->empty_table('mytable'); // Produces: DELETE FROM mytable
$this->db->truncate()
truncate SQL 문자열을 생성하고 해당 쿼리를 실행합니다.
$this->db->from('mytable');
$this->db->truncate();
// or
$this->db->truncate('mytable');
// Produce:
// TRUNCATE mytable
주의사항
TRUNCATE 명령을 사용할 수 없으면, "truncate()" 메소드는 "DELETE FROM table" 구문으로 대체되어 실행됩니다.
$this->db->get_compiled_delete()
이 함수는 INSERT SQL 문자열 대신 DELETE SQL 문자열을 생성한다는 점을 제외하고, "$this->db->get_compiled_insert()" 메소드와 똑같은 방식으로 작동됩니다.
더 자세한 내용은 "$this->db->get_compiled_insert()" 설명 내용을 참조하세요.
메소드 체이닝(Chaining)
메서드 체이닝을 사용하면 멀티 함수를 연결하여 구문을 단순화할 수 있습니다.
다음 예를 살펴보세요 :
$query = $this->db->select('title')
->where('id', $id)
->limit(10, 20)
->get('mytable');
쿼리 빌더 캐싱
쿼리 빌더는 스크립트 실행 후 나중 시점에 쿼리 중 특정 부분을 재사용할 수 있도록 해당 쿼리를 저장(또는 "캐시")할 수 있습니다.
일반적으로 쿼리 빌더 호출이 완료되면 저장된 모든 정보가 다음 호출을 위해 리셋됩니다.
캐싱을 사용하면, 이 리셋을 막고 정보를 쉽게 재사용할 수 있습니다.
캐시된 호출은 계속 누적됩니다.
2개의 캐시된 select() 호출과 2개의 캐시되지 않은 select() 호출을 수행하면 4개의 select() 호출이 발생할 것입니다.
세 개의 캐싱 함수를 사용할 수 있습니다 :
$this->db->start_cache()
캐싱을 시작하려면 이 함수를 호출해야 합니다.
올바른 유형의 모든 쿼리 빌더 쿼리들은 (지원되는 쿼리는 아래 참조) 재사용되기 위해 저장됩니다.
$this->db->stop_cache()
이 함수는 캐싱을 중지하기 위해 호출 할 수 있습니다.
$this->db->flush_cache()
이 함수는 쿼리 빌더 캐시로부터 모든 항목을 삭제합니다.
캐싱에 대한 예제
다음 사용 예제입니다 :
$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
$this->db->get('tablename');
//Generates: SELECT `field1` FROM (`tablename`)
$this->db->select('field2');
$this->db->get('tablename');
//Generates: SELECT `field1`, `field2` FROM (`tablename`)
$this->db->flush_cache();
$this->db->select('field2');
$this->db->get('tablename');
//Generates: SELECT `field2` FROM (`tablename`)
주의사항
다음 구문을 캐시 할 수 있습니다 : select, from, join, where, like, group_by, having, order_by
쿼리 빌더 리셋
$this->db->reset_query()
쿼리 빌더를 리셋하면 "$this->db->get()" 또는 "$this->db->insert()"와 같은 메소드를 사용하지 않고도 쿼리를 새로 시작할 수 있습니다.
쿼리 실행 메소드들과 마찬가지로 쿼리 빌더 캐싱을 통해 이미 캐시된 항목은 리셋되지 않습니다.
이 함수는 쿼리 빌더를 사용하여 SQL을 생성하고(예 : $this->db->get_compiled_select()) 해당 쿼리를 실행하도록 선택하는 경우에만 유용합니다. (예입니다) :
// get_compiled_select 메소드의 두 번째 매개 변수가 FALSE임에 유의하세요
$sql = $this->db->select(array('field1','field2'))
->where('field3',5)
->get_compiled_select('mytable', FALSE);
// ...
// 해당 SQL 코드로 잘못된 작업을 실행합니다..... cron 스크립트(주기적 반복 스크립트)에 추가하는 것과 같은 작업입니다...
// 추후에 실행하거나 다른 작업을 함....
// ...
$data = $this->db->get()->result_array();
// 다음 쿼리를 실행한 후 그 결과를 배열로 반환합니다 :
// SELECT field1, field1 from mytable where field3 = 5;
주의사항
쿼리 빌더 캐싱 기능을 사용하면서 당신의 쿼리를 리셋하지 않는다면 "get_compiled_select()를 두 번 호출하여 그 결과가 두 번 병합됩니다.
예를 들어, "select()"를 캐싱하는 경우라면, 같은 필드가 두 번 "select"됩니다.