blob: 577248b3235ffad8ca3f2088e0290050892ab2c1 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001###################
Jamie Rumbelow7efad202012-02-19 12:37:00 +00002Query Builder Class
Derek Jones8ede1a22011-10-05 13:34:52 -05003###################
4
Jamie Rumbelow7efad202012-02-19 12:37:00 +00005CodeIgniter gives you access to a Query Builder class. This pattern
6allows information to be retrieved, inserted, and updated in your
7database with minimal scripting. In some cases only one or two lines
8of code are necessary to perform a database action.
Derek Jones8ede1a22011-10-05 13:34:52 -05009CodeIgniter does not require that each database table be its own class
10file. It instead provides a more simplified interface.
11
Jamie Rumbelow7efad202012-02-19 12:37:00 +000012Beyond simplicity, a major benefit to using the Query Builder features
Derek Jones8ede1a22011-10-05 13:34:52 -050013is that it allows you to create database independent applications, since
14the query syntax is generated by each database adapter. It also allows
15for safer queries, since the values are escaped automatically by the
16system.
17
18.. note:: If you intend to write your own queries you can disable this
19 class in your database config file, allowing the core database library
20 and adapter to utilize fewer resources.
21
James L Parry42a7df62014-11-25 12:06:49 -080022.. contents::
23 :local:
24 :depth: 1
Derek Jones8ede1a22011-10-05 13:34:52 -050025
26**************
27Selecting Data
28**************
29
30The following functions allow you to build SQL **SELECT** statements.
31
James L Parry141288d2014-12-06 01:45:12 -080032**$this->db->get()**
Derek Jones8ede1a22011-10-05 13:34:52 -050033
34Runs the selection query and returns the result. Can be used by itself
35to retrieve all records from a table::
36
37 $query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable
38
39The second and third parameters enable you to set a limit and offset
40clause::
41
42 $query = $this->db->get('mytable', 10, 20);
James L Parry42a7df62014-11-25 12:06:49 -080043 // Produces: SELECT * FROM mytable LIMIT 20, 10
44 // (in MySQL. Other databases have slightly different syntax)
Derek Jones8ede1a22011-10-05 13:34:52 -050045
46You'll notice that the above function is assigned to a variable named
47$query, which can be used to show the results::
48
49 $query = $this->db->get('mytable');
WanWizard7219c072011-12-28 14:09:05 +010050
Derek Jones8ede1a22011-10-05 13:34:52 -050051 foreach ($query->result() as $row)
52 {
53 echo $row->title;
54 }
55
56Please visit the :doc:`result functions <results>` page for a full
57discussion regarding result generation.
58
James L Parry141288d2014-12-06 01:45:12 -080059**$this->db->get_compiled_select()**
James L Parry42a7df62014-11-25 12:06:49 -080060
61Compiles the selection query just like **$this->db->get()** but does not *run*
Kyle Farris48d8fb62011-10-14 17:59:49 -030062the query. This method simply returns the SQL query as a string.
63
64Example::
65
66 $sql = $this->db->get_compiled_select('mytable');
67 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +010068
Kyle Farris48d8fb62011-10-14 17:59:49 -030069 // Produces string: SELECT * FROM mytable
WanWizard7219c072011-12-28 14:09:05 +010070
Jamie Rumbelow7efad202012-02-19 12:37:00 +000071The second parameter enables you to set whether or not the query builder query
GDmac01e9fb12013-11-09 08:01:52 +010072will be reset (by default it will be reset, just like when using `$this->db->get()`)::
Kyle Farris48d8fb62011-10-14 17:59:49 -030073
74 echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);
WanWizard7219c072011-12-28 14:09:05 +010075 // Produces string: SELECT * FROM mytable LIMIT 20, 10
Kyle Farris48d8fb62011-10-14 17:59:49 -030076 // (in MySQL. Other databases have slightly different syntax)
WanWizard7219c072011-12-28 14:09:05 +010077
Kyle Farris48d8fb62011-10-14 17:59:49 -030078 echo $this->db->select('title, content, date')->get_compiled_select();
79
GDmac01e9fb12013-11-09 08:01:52 +010080 // Produces string: SELECT title, content, date FROM mytable LIMIT 20, 10
WanWizard7219c072011-12-28 14:09:05 +010081
82The key thing to notice in the above example is that the second query did not
James L Parry42a7df62014-11-25 12:06:49 -080083utilize **$this->db->from()** and did not pass a table name into the first
WanWizard7219c072011-12-28 14:09:05 +010084parameter. The reason for this outcome is because the query has not been
James L Parry42a7df62014-11-25 12:06:49 -080085executed using **$this->db->get()** which resets values or reset directly
86using **$this->db->reset_query()**.
Kyle Farris48d8fb62011-10-14 17:59:49 -030087
James L Parry141288d2014-12-06 01:45:12 -080088**$this->db->get_where()**
Derek Jones8ede1a22011-10-05 13:34:52 -050089
90Identical to the above function except that it permits you to add a
91"where" clause in the second parameter, instead of using the db->where()
92function::
93
94 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
95
96Please read the about the where function below for more information.
97
Greg Akerffd24a42011-12-25 22:27:59 -060098.. note:: get_where() was formerly known as getwhere(), which has been removed
Derek Jones8ede1a22011-10-05 13:34:52 -050099
James L Parry141288d2014-12-06 01:45:12 -0800100**$this->db->select()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500101
102Permits you to write the SELECT portion of your query::
103
104 $this->db->select('title, content, date');
105 $query = $this->db->get('mytable'); // Produces: SELECT title, content, date FROM mytable
106
107
108.. note:: If you are selecting all (\*) from a table you do not need to
109 use this function. When omitted, CodeIgniter assumes you wish to SELECT *
110
111$this->db->select() accepts an optional second parameter. If you set it
112to FALSE, CodeIgniter will not try to protect your field or table names
113with backticks. This is useful if you need a compound select statement.
114
115::
116
WanWizard7219c072011-12-28 14:09:05 +0100117 $this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
Derek Jones8ede1a22011-10-05 13:34:52 -0500118 $query = $this->db->get('mytable');
119
James L Parry141288d2014-12-06 01:45:12 -0800120**$this->db->select_max()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500121
122Writes a "SELECT MAX(field)" portion for your query. You can optionally
123include a second parameter to rename the resulting field.
124
125::
126
127 $this->db->select_max('age');
128 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members
WanWizard7219c072011-12-28 14:09:05 +0100129
Derek Jones8ede1a22011-10-05 13:34:52 -0500130 $this->db->select_max('age', 'member_age');
131 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members
132
133
James L Parry42a7df62014-11-25 12:06:49 -0800134**$this->db->select_min()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500135
136Writes a "SELECT MIN(field)" portion for your query. As with
137select_max(), You can optionally include a second parameter to rename
138the resulting field.
139
140::
141
142 $this->db->select_min('age');
143 $query = $this->db->get('members'); // Produces: SELECT MIN(age) as age FROM members
144
145
James L Parry42a7df62014-11-25 12:06:49 -0800146**$this->db->select_avg()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500147
148Writes a "SELECT AVG(field)" portion for your query. As with
149select_max(), You can optionally include a second parameter to rename
150the resulting field.
151
152::
153
154 $this->db->select_avg('age');
155 $query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
156
157
James L Parry42a7df62014-11-25 12:06:49 -0800158**$this->db->select_sum()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500159
160Writes a "SELECT SUM(field)" portion for your query. As with
161select_max(), You can optionally include a second parameter to rename
162the resulting field.
163
164::
165
166 $this->db->select_sum('age');
167 $query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members
168
James L Parry141288d2014-12-06 01:45:12 -0800169**$this->db->from()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500170
171Permits you to write the FROM portion of your query::
172
173 $this->db->select('title, content, date');
174 $this->db->from('mytable');
175 $query = $this->db->get(); // Produces: SELECT title, content, date FROM mytable
176
177.. note:: As shown earlier, the FROM portion of your query can be specified
178 in the $this->db->get() function, so use whichever method you prefer.
179
James L Parry141288d2014-12-06 01:45:12 -0800180**$this->db->join()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500181
182Permits you to write the JOIN portion of your query::
183
184 $this->db->select('*');
185 $this->db->from('blogs');
186 $this->db->join('comments', 'comments.id = blogs.id');
187 $query = $this->db->get();
WanWizard7219c072011-12-28 14:09:05 +0100188
Derek Jones8ede1a22011-10-05 13:34:52 -0500189 // Produces:
kenjisc35d2c92011-10-26 17:09:17 +0900190 // SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Derek Jones8ede1a22011-10-05 13:34:52 -0500191
192Multiple function calls can be made if you need several joins in one
193query.
194
195If you need a specific type of JOIN you can specify it via the third
196parameter of the function. Options are: left, right, outer, inner, left
197outer, and right outer.
198
199::
200
201 $this->db->join('comments', 'comments.id = blogs.id', 'left');
202 // Produces: LEFT JOIN comments ON comments.id = blogs.id
203
James L Parry42a7df62014-11-25 12:06:49 -0800204*************************
205Looking for Specific Data
206*************************
207
James L Parry141288d2014-12-06 01:45:12 -0800208**$this->db->where()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500209
210This function enables you to set **WHERE** clauses using one of four
211methods:
212
213.. note:: All values passed to this function are escaped automatically,
214 producing safer queries.
215
216#. **Simple key/value method:**
217
218 ::
219
WanWizard7219c072011-12-28 14:09:05 +0100220 $this->db->where('name', $name); // Produces: WHERE name = 'Joe'
Derek Jones8ede1a22011-10-05 13:34:52 -0500221
222 Notice that the equal sign is added for you.
223
224 If you use multiple function calls they will be chained together with
225 AND between them:
226
227 ::
228
229 $this->db->where('name', $name);
230 $this->db->where('title', $title);
231 $this->db->where('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100232 // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500233
234#. **Custom key/value method:**
235 You can include an operator in the first parameter in order to
236 control the comparison:
237
238 ::
239
240 $this->db->where('name !=', $name);
WanWizard7219c072011-12-28 14:09:05 +0100241 $this->db->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500242
243#. **Associative array method:**
244
245 ::
246
247 $array = array('name' => $name, 'title' => $title, 'status' => $status);
248 $this->db->where($array);
WanWizard7219c072011-12-28 14:09:05 +0100249 // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500250
251 You can include your own operators using this method as well:
252
253 ::
254
255 $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
256 $this->db->where($array);
257
258#. **Custom string:**
259 You can write your own clauses manually::
260
261 $where = "name='Joe' AND status='boss' OR status='active'";
262 $this->db->where($where);
263
264
265$this->db->where() accepts an optional third parameter. If you set it to
266FALSE, CodeIgniter will not try to protect your field or table names
267with backticks.
268
269::
270
271 $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
272
James L Parry42a7df62014-11-25 12:06:49 -0800273**$this->db->or_where()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500274
275This function is identical to the one above, except that multiple
276instances are joined by OR::
277
278 $this->db->where('name !=', $name);
279 $this->db->or_where('id >', $id); // Produces: WHERE name != 'Joe' OR id > 50
280
281.. note:: or_where() was formerly known as orwhere(), which has been
282 removed.
283
James L Parry141288d2014-12-06 01:45:12 -0800284**$this->db->where_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500285
286Generates a WHERE field IN ('item', 'item') SQL query joined with AND if
287appropriate
288
289::
290
291 $names = array('Frank', 'Todd', 'James');
292 $this->db->where_in('username', $names);
293 // Produces: WHERE username IN ('Frank', 'Todd', 'James')
294
295
James L Parry42a7df62014-11-25 12:06:49 -0800296**$this->db->or_where_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500297
298Generates a WHERE field IN ('item', 'item') SQL query joined with OR if
299appropriate
300
301::
302
303 $names = array('Frank', 'Todd', 'James');
304 $this->db->or_where_in('username', $names);
305 // Produces: OR username IN ('Frank', 'Todd', 'James')
306
James L Parry141288d2014-12-06 01:45:12 -0800307**$this->db->where_not_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500308
309Generates a WHERE field NOT IN ('item', 'item') SQL query joined with
310AND if appropriate
311
312::
313
314 $names = array('Frank', 'Todd', 'James');
315 $this->db->where_not_in('username', $names);
316 // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')
317
318
James L Parry42a7df62014-11-25 12:06:49 -0800319**$this->db->or_where_not_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500320
321Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR
322if appropriate
323
324::
325
326 $names = array('Frank', 'Todd', 'James');
327 $this->db->or_where_not_in('username', $names);
328 // Produces: OR username NOT IN ('Frank', 'Todd', 'James')
329
James L Parry42a7df62014-11-25 12:06:49 -0800330************************
331Looking for Similar Data
332************************
Derek Jones8ede1a22011-10-05 13:34:52 -0500333
James L Parry141288d2014-12-06 01:45:12 -0800334**$this->db->like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500335
Andrey Andreev41738232012-11-30 00:13:17 +0200336This method enables you to generate **LIKE** clauses, useful for doing
Derek Jones8ede1a22011-10-05 13:34:52 -0500337searches.
338
Andrey Andreev41738232012-11-30 00:13:17 +0200339.. note:: All values passed to this method are escaped automatically.
Derek Jones8ede1a22011-10-05 13:34:52 -0500340
341#. **Simple key/value method:**
342
343 ::
344
Andrey Andreev41738232012-11-30 00:13:17 +0200345 $this->db->like('title', 'match');
346 // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500347
Andrey Andreev41738232012-11-30 00:13:17 +0200348 If you use multiple method calls they will be chained together with
Derek Jones8ede1a22011-10-05 13:34:52 -0500349 AND between them::
350
351 $this->db->like('title', 'match');
352 $this->db->like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200353 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500354
355 If you want to control where the wildcard (%) is placed, you can use
356 an optional third argument. Your options are 'before', 'after' and
357 'both' (which is the default).
358
359 ::
360
Andrey Andreev41738232012-11-30 00:13:17 +0200361 $this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
362 $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
363 $this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500364
365#. **Associative array method:**
366
367 ::
368
369 $array = array('title' => $match, 'page1' => $match, 'page2' => $match);
370 $this->db->like($array);
Andrey Andreev41738232012-11-30 00:13:17 +0200371 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500372
373
James L Parry42a7df62014-11-25 12:06:49 -0800374**$this->db->or_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500375
Andrey Andreev41738232012-11-30 00:13:17 +0200376This method is identical to the one above, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500377instances are joined by OR::
378
379 $this->db->like('title', 'match'); $this->db->or_like('body', $match);
Andrey Andreev41738232012-11-30 00:13:17 +0200380 // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500381
Andrey Andreev41738232012-11-30 00:13:17 +0200382.. note:: ``or_like()`` was formerly known as ``orlike()``, which has been removed.
Derek Jones8ede1a22011-10-05 13:34:52 -0500383
James L Parry42a7df62014-11-25 12:06:49 -0800384**$this->db->not_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500385
Andrey Andreev41738232012-11-30 00:13:17 +0200386This method is identical to ``like()``, except that it generates
387NOT LIKE statements::
Derek Jones8ede1a22011-10-05 13:34:52 -0500388
Andrey Andreev41738232012-11-30 00:13:17 +0200389 $this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500390
James L Parry42a7df62014-11-25 12:06:49 -0800391**$this->db->or_not_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500392
Andrey Andreev41738232012-11-30 00:13:17 +0200393This method is identical to ``not_like()``, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500394instances are joined by OR::
395
396 $this->db->like('title', 'match');
397 $this->db->or_not_like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200398 // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500399
James L Parry141288d2014-12-06 01:45:12 -0800400**$this->db->group_by()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500401
402Permits you to write the GROUP BY portion of your query::
403
404 $this->db->group_by("title"); // Produces: GROUP BY title
405
406You can also pass an array of multiple values as well::
407
408 $this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
409
410.. note:: group_by() was formerly known as groupby(), which has been
411 removed.
412
James L Parry141288d2014-12-06 01:45:12 -0800413**$this->db->distinct()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500414
415Adds the "DISTINCT" keyword to a query
416
417::
418
419 $this->db->distinct();
420 $this->db->get('table'); // Produces: SELECT DISTINCT * FROM table
421
James L Parry141288d2014-12-06 01:45:12 -0800422**$this->db->having()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500423
424Permits you to write the HAVING portion of your query. There are 2
425possible syntaxes, 1 argument or 2::
426
427 $this->db->having('user_id = 45'); // Produces: HAVING user_id = 45
WanWizard7219c072011-12-28 14:09:05 +0100428 $this->db->having('user_id', 45); // Produces: HAVING user_id = 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500429
430You can also pass an array of multiple values as well::
431
432 $this->db->having(array('title =' => 'My Title', 'id <' => $id));
433 // Produces: HAVING title = 'My Title', id < 45
434
435
436If you are using a database that CodeIgniter escapes queries for, you
437can prevent escaping content by passing an optional third argument, and
438setting it to FALSE.
439
440::
441
442 $this->db->having('user_id', 45); // Produces: HAVING `user_id` = 45 in some databases such as MySQL
443 $this->db->having('user_id', 45, FALSE); // Produces: HAVING user_id = 45
444
445
James L Parry42a7df62014-11-25 12:06:49 -0800446**$this->db->or_having()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500447
448Identical to having(), only separates multiple clauses with "OR".
449
James L Parry42a7df62014-11-25 12:06:49 -0800450****************
451Ordering results
452****************
453
James L Parry141288d2014-12-06 01:45:12 -0800454**$this->db->order_by()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500455
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200456Lets you set an ORDER BY clause.
457
458The first parameter contains the name of the column you would like to order by.
459
460The second parameter lets you set the direction of the result.
461Options are **ASC**, **DESC** AND **RANDOM**.
Derek Jones8ede1a22011-10-05 13:34:52 -0500462
463::
464
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200465 $this->db->order_by('title', 'DESC');
466 // Produces: ORDER BY `title` DESC
Derek Jones8ede1a22011-10-05 13:34:52 -0500467
468You can also pass your own string in the first parameter::
469
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200470 $this->db->order_by('title DESC, name ASC');
471 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500472
473Or multiple function calls can be made if you need multiple fields.
474
475::
476
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200477 $this->db->order_by('title', 'DESC');
478 $this->db->order_by('name', 'ASC');
479 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500480
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200481If you choose the **RANDOM** direction option, then the first parameters will
482be ignored, unless you specify a numeric seed value.
483
484::
485
486 $this->db->order_by('title', 'RANDOM');
487 // Produces: ORDER BY RAND()
488
489 $this->db->order_by(42, 'RANDOM');
490 // Produces: ORDER BY RAND(42)
Derek Jones8ede1a22011-10-05 13:34:52 -0500491
492.. note:: order_by() was formerly known as orderby(), which has been
493 removed.
494
Andrey Andreev0dfb62f2012-10-30 11:37:15 +0200495.. note:: Random ordering is not currently supported in Oracle and
496 will default to ASC instead.
Derek Jones8ede1a22011-10-05 13:34:52 -0500497
James L Parry42a7df62014-11-25 12:06:49 -0800498****************************
499Limiting or Counting Results
500****************************
501
James L Parry141288d2014-12-06 01:45:12 -0800502**$this->db->limit()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500503
504Lets you limit the number of rows you would like returned by the query::
505
506 $this->db->limit(10); // Produces: LIMIT 10
507
508The second parameter lets you set a result offset.
509
510::
511
512 $this->db->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
513
James L Parry141288d2014-12-06 01:45:12 -0800514**$this->db->count_all_results()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500515
516Permits you to determine the number of rows in a particular Active
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000517Record query. Queries will accept Query Builder restrictors such as
Derek Jones8ede1a22011-10-05 13:34:52 -0500518where(), or_where(), like(), or_like(), etc. Example::
519
520 echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
521 $this->db->like('title', 'match');
522 $this->db->from('my_table');
WanWizard7219c072011-12-28 14:09:05 +0100523 echo $this->db->count_all_results(); // Produces an integer, like 17
Derek Jones8ede1a22011-10-05 13:34:52 -0500524
James L Parry141288d2014-12-06 01:45:12 -0800525**$this->db->count_all()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500526
527Permits you to determine the number of rows in a particular table.
528Submit the table name in the first parameter. Example::
529
530 echo $this->db->count_all('my_table'); // Produces an integer, like 25
531
532**************
WanWizard7219c072011-12-28 14:09:05 +0100533Query grouping
534**************
535
536Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow
Timothy Warrene464b392012-03-13 14:09:31 -0400537you to create queries with complex WHERE clauses. Nested groups are supported. Example::
WanWizard7219c072011-12-28 14:09:05 +0100538
539 $this->db->select('*')->from('my_table')
540 ->group_start()
541 ->where('a', 'a')
542 ->or_group_start()
543 ->where('b', 'b')
544 ->where('c', 'c')
545 ->group_end()
546 ->group_end()
547 ->where('d', 'd')
548 ->get();
549
550 // Generates:
551 // SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
552
553.. note:: groups need to be balanced, make sure every group_start() is matched by a group_end().
554
James L Parry42a7df62014-11-25 12:06:49 -0800555**$this->db->group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100556
557Starts a new group by adding an opening parenthesis to the WHERE clause of the query.
558
James L Parry42a7df62014-11-25 12:06:49 -0800559**$this->db->or_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100560
561Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR'.
562
James L Parry42a7df62014-11-25 12:06:49 -0800563**$this->db->not_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100564
565Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'NOT'.
566
James L Parry42a7df62014-11-25 12:06:49 -0800567**$this->db->or_not_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100568
569Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR NOT'.
570
James L Parry42a7df62014-11-25 12:06:49 -0800571**$this->db->group_end()**
WanWizard7219c072011-12-28 14:09:05 +0100572
573Ends the current group by adding an closing parenthesis to the WHERE clause of the query.
574
575**************
Derek Jones8ede1a22011-10-05 13:34:52 -0500576Inserting Data
577**************
578
James L Parry141288d2014-12-06 01:45:12 -0800579**$this->db->insert()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500580
581Generates an insert string based on the data you supply, and runs the
582query. You can either pass an **array** or an **object** to the
583function. Here is an example using an array::
584
585 $data = array(
586 'title' => 'My title',
587 'name' => 'My Name',
588 'date' => 'My date'
589 );
WanWizard7219c072011-12-28 14:09:05 +0100590
Derek Jones8ede1a22011-10-05 13:34:52 -0500591 $this->db->insert('mytable', $data);
592 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
593
594The first parameter will contain the table name, the second is an
595associative array of values.
596
597Here is an example using an object::
598
599 /*
600 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200601 public $title = 'My Title';
602 public $content = 'My Content';
603 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500604 }
605 */
WanWizard7219c072011-12-28 14:09:05 +0100606
Derek Jones8ede1a22011-10-05 13:34:52 -0500607 $object = new Myclass;
608 $this->db->insert('mytable', $object);
609 // Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
610
611The first parameter will contain the table name, the second is an
612object.
613
614.. note:: All values are escaped automatically producing safer queries.
615
James L Parry141288d2014-12-06 01:45:12 -0800616**$this->db->get_compiled_insert()**
James L Parry42a7df62014-11-25 12:06:49 -0800617
James L Parry141288d2014-12-06 01:45:12 -0800618Compiles the insertion query just like $this->db->insert() but does not
Kyle Farris48d8fb62011-10-14 17:59:49 -0300619*run* the query. This method simply returns the SQL query as a string.
620
621Example::
622
623 $data = array(
624 'title' => 'My title',
625 'name' => 'My Name',
626 'date' => 'My date'
627 );
WanWizard7219c072011-12-28 14:09:05 +0100628
Kyle Farris48d8fb62011-10-14 17:59:49 -0300629 $sql = $this->db->set($data)->get_compiled_insert('mytable');
630 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +0100631
Kyle Farris48d8fb62011-10-14 17:59:49 -0300632 // Produces string: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
633
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000634The second parameter enables you to set whether or not the query builder query
James L Parry141288d2014-12-06 01:45:12 -0800635will be reset (by default it will be--just like $this->db->insert())::
WanWizard7219c072011-12-28 14:09:05 +0100636
Kyle Farris48d8fb62011-10-14 17:59:49 -0300637 echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);
WanWizard7219c072011-12-28 14:09:05 +0100638
Kyle Farris48d8fb62011-10-14 17:59:49 -0300639 // Produces string: INSERT INTO mytable (title) VALUES ('My Title')
WanWizard7219c072011-12-28 14:09:05 +0100640
Kyle Farris48d8fb62011-10-14 17:59:49 -0300641 echo $this->db->set('content', 'My Content')->get_compiled_insert();
642
643 // Produces string: INSERT INTO mytable (title, content) VALUES ('My Title', 'My Content')
WanWizard7219c072011-12-28 14:09:05 +0100644
645The key thing to notice in the above example is that the second query did not
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200646utlize `$this->db->from()` nor did it pass a table name into the first
WanWizard7219c072011-12-28 14:09:05 +0100647parameter. The reason this worked is because the query has not been executed
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200648using `$this->db->insert()` which resets values or reset directly using
649`$this->db->reset_query()`.
650
651.. note:: This method doesn't work for batched inserts.
Kyle Farris48d8fb62011-10-14 17:59:49 -0300652
James L Parry141288d2014-12-06 01:45:12 -0800653**$this->db->insert_batch()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500654
655Generates an insert string based on the data you supply, and runs the
656query. You can either pass an **array** or an **object** to the
657function. Here is an example using an array::
658
659 $data = array(
660 array(
661 'title' => 'My title',
662 'name' => 'My Name',
663 'date' => 'My date'
664 ),
665 array(
666 'title' => 'Another title',
667 'name' => 'Another Name',
668 'date' => 'Another date'
669 )
670 );
WanWizard7219c072011-12-28 14:09:05 +0100671
Derek Jones8ede1a22011-10-05 13:34:52 -0500672 $this->db->insert_batch('mytable', $data);
673 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
674
675The first parameter will contain the table name, the second is an
676associative array of values.
677
678.. note:: All values are escaped automatically producing safer queries.
679
James L Parry42a7df62014-11-25 12:06:49 -0800680*************
681Updating Data
682*************
683
James L Parry141288d2014-12-06 01:45:12 -0800684**$this->db->replace()**
Andrey Andreev04c50f52012-10-24 23:05:25 +0300685
686This method executes a REPLACE statement, which is basically the SQL
687standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE*
688keys as the determining factor.
689In our case, it will save you from the need to implement complex
690logics with different combinations of ``select()``, ``update()``,
691``delete()`` and ``insert()`` calls.
692
693Example::
694
695 $data = array(
696 'title' => 'My title',
697 'name' => 'My Name',
698 'date' => 'My date'
699 );
700
701 $this->db->replace('table', $data);
702
703 // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
704
705In the above example, if we assume that the *title* field is our primary
706key, then if a row containing 'My title' as the *title* value, that row
707will be deleted with our new row data replacing it.
708
709Usage of the ``set()`` method is also allowed and all fields are
710automatically escaped, just like with ``insert()``.
711
James L Parry141288d2014-12-06 01:45:12 -0800712**$this->db->set()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500713
714This function enables you to set values for inserts or updates.
715
716**It can be used instead of passing a data array directly to the insert
717or update functions:**
718
719::
720
721 $this->db->set('name', $name);
722 $this->db->insert('mytable'); // Produces: INSERT INTO mytable (name) VALUES ('{$name}')
723
724If you use multiple function called they will be assembled properly
725based on whether you are doing an insert or an update::
726
727 $this->db->set('name', $name);
728 $this->db->set('title', $title);
729 $this->db->set('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100730 $this->db->insert('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500731
732**set()** will also accept an optional third parameter ($escape), that
733will prevent data from being escaped if set to FALSE. To illustrate the
734difference, here is set() used both with and without the escape
735parameter.
736
737::
738
739 $this->db->set('field', 'field+1', FALSE);
740 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES (field+1)
741 $this->db->set('field', 'field+1');
742 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES ('field+1')
743
744
745You can also pass an associative array to this function::
746
747 $array = array(
748 'name' => $name,
749 'title' => $title,
750 'status' => $status
751 );
WanWizard7219c072011-12-28 14:09:05 +0100752
Derek Jones8ede1a22011-10-05 13:34:52 -0500753 $this->db->set($array);
754 $this->db->insert('mytable');
755
756Or an object::
757
758 /*
759 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200760 public $title = 'My Title';
761 public $content = 'My Content';
762 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500763 }
764 */
WanWizard7219c072011-12-28 14:09:05 +0100765
Derek Jones8ede1a22011-10-05 13:34:52 -0500766 $object = new Myclass;
767 $this->db->set($object);
768 $this->db->insert('mytable');
769
James L Parry141288d2014-12-06 01:45:12 -0800770**$this->db->update()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500771
772Generates an update string and runs the query based on the data you
773supply. You can pass an **array** or an **object** to the function. Here
774is an example using an array::
775
776 $data = array(
777 'title' => $title,
778 'name' => $name,
779 'date' => $date
780 );
WanWizard7219c072011-12-28 14:09:05 +0100781
Derek Jones8ede1a22011-10-05 13:34:52 -0500782 $this->db->where('id', $id);
783 $this->db->update('mytable', $data);
784 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
785
786Or you can supply an object::
787
788 /*
789 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200790 public $title = 'My Title';
791 public $content = 'My Content';
792 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500793 }
794 */
WanWizard7219c072011-12-28 14:09:05 +0100795
Derek Jones8ede1a22011-10-05 13:34:52 -0500796 $object = new Myclass;
797 $this->db->where('id', $id);
798 $this->db->update('mytable', $object);
799 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
800
801.. note:: All values are escaped automatically producing safer queries.
802
803You'll notice the use of the $this->db->where() function, enabling you
804to set the WHERE clause. You can optionally pass this information
805directly into the update function as a string::
806
807 $this->db->update('mytable', $data, "id = 4");
808
809Or as an array::
810
811 $this->db->update('mytable', $data, array('id' => $id));
812
813You may also use the $this->db->set() function described above when
814performing updates.
815
James L Parry141288d2014-12-06 01:45:12 -0800816**$this->db->update_batch()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500817
818Generates an update string based on the data you supply, and runs the query.
819You can either pass an **array** or an **object** to the function.
820Here is an example using an array::
821
822 $data = array(
823 array(
824 'title' => 'My title' ,
825 'name' => 'My Name 2' ,
826 'date' => 'My date 2'
827 ),
828 array(
829 'title' => 'Another title' ,
830 'name' => 'Another Name 2' ,
831 'date' => 'Another date 2'
832 )
833 );
834
WanWizard7219c072011-12-28 14:09:05 +0100835 $this->db->update_batch('mytable', $data, 'title');
Derek Jones8ede1a22011-10-05 13:34:52 -0500836
WanWizard7219c072011-12-28 14:09:05 +0100837 // Produces:
Derek Jones8ede1a22011-10-05 13:34:52 -0500838 // UPDATE `mytable` SET `name` = CASE
839 // WHEN `title` = 'My title' THEN 'My Name 2'
840 // WHEN `title` = 'Another title' THEN 'Another Name 2'
841 // ELSE `name` END,
WanWizard7219c072011-12-28 14:09:05 +0100842 // `date` = CASE
Derek Jones8ede1a22011-10-05 13:34:52 -0500843 // WHEN `title` = 'My title' THEN 'My date 2'
844 // WHEN `title` = 'Another title' THEN 'Another date 2'
845 // ELSE `date` END
846 // WHERE `title` IN ('My title','Another title')
847
848The first parameter will contain the table name, the second is an associative
849array of values, the third parameter is the where key.
850
851.. note:: All values are escaped automatically producing safer queries.
852
Andrey Andreev9f808b02012-10-24 17:38:48 +0300853.. note:: ``affected_rows()`` won't give you proper results with this method,
854 due to the very nature of how it works. Instead, ``update_batch()``
855 returns the number of rows affected.
856
James L Parry141288d2014-12-06 01:45:12 -0800857**$this->db->get_compiled_update()**
Kyle Farris48d8fb62011-10-14 17:59:49 -0300858
859This works exactly the same way as ``$this->db->get_compiled_insert()`` except
860that it produces an UPDATE SQL string instead of an INSERT SQL string.
861
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200862For more information view documentation for `$this->db->get_compiled_insert()`.
Kyle Farris48d8fb62011-10-14 17:59:49 -0300863
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200864.. note:: This method doesn't work for batched updates.
Derek Jones8ede1a22011-10-05 13:34:52 -0500865
866*************
867Deleting Data
868*************
869
James L Parry141288d2014-12-06 01:45:12 -0800870**$this->db->delete()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500871
872Generates a delete SQL string and runs the query.
873
874::
875
876 $this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
877
878The first parameter is the table name, the second is the where clause.
879You can also use the where() or or_where() functions instead of passing
880the data to the second parameter of the function::
881
882 $this->db->where('id', $id);
883 $this->db->delete('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100884
Derek Jones8ede1a22011-10-05 13:34:52 -0500885 // Produces:
886 // DELETE FROM mytable
887 // WHERE id = $id
888
889
890An array of table names can be passed into delete() if you would like to
891delete data from more than 1 table.
892
893::
894
895 $tables = array('table1', 'table2', 'table3');
896 $this->db->where('id', '5');
897 $this->db->delete($tables);
898
899
900If you want to delete all data from a table, you can use the truncate()
901function, or empty_table().
902
James L Parry141288d2014-12-06 01:45:12 -0800903**$this->db->empty_table()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500904
905Generates a delete SQL string and runs the
906query.::
907
kenjisc35d2c92011-10-26 17:09:17 +0900908 $this->db->empty_table('mytable'); // Produces: DELETE FROM mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500909
James L Parry141288d2014-12-06 01:45:12 -0800910**$this->db->truncate()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500911
912Generates a truncate SQL string and runs the query.
913
914::
915
916 $this->db->from('mytable');
kenjisc35d2c92011-10-26 17:09:17 +0900917 $this->db->truncate();
WanWizard7219c072011-12-28 14:09:05 +0100918
919 // or
920
Derek Jones8ede1a22011-10-05 13:34:52 -0500921 $this->db->truncate('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100922
Derek Jones8ede1a22011-10-05 13:34:52 -0500923 // Produce:
WanWizard7219c072011-12-28 14:09:05 +0100924 // TRUNCATE mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500925
926.. note:: If the TRUNCATE command isn't available, truncate() will
927 execute as "DELETE FROM table".
WanWizard7219c072011-12-28 14:09:05 +0100928
James L Parry141288d2014-12-06 01:45:12 -0800929**$this->db->get_compiled_delete()**
James L Parry42a7df62014-11-25 12:06:49 -0800930
Kyle Farris48d8fb62011-10-14 17:59:49 -0300931This works exactly the same way as ``$this->db->get_compiled_insert()`` except
932that it produces a DELETE SQL string instead of an INSERT SQL string.
933
James L Parry141288d2014-12-06 01:45:12 -0800934For more information view documentation for $this->db->get_compiled_insert().
James L Parry42a7df62014-11-25 12:06:49 -0800935
Derek Jones8ede1a22011-10-05 13:34:52 -0500936***************
937Method Chaining
938***************
939
940Method chaining allows you to simplify your syntax by connecting
941multiple functions. Consider this example::
942
943 $query = $this->db->select('title')
Timothy Warrene464b392012-03-13 14:09:31 -0400944 ->where('id', $id)
945 ->limit(10, 20)
946 ->get('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500947
Derek Jones8ede1a22011-10-05 13:34:52 -0500948.. _ar-caching:
949
950*********************
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000951Query Builder Caching
Derek Jones8ede1a22011-10-05 13:34:52 -0500952*********************
953
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000954While not "true" caching, Query Builder enables you to save (or "cache")
Derek Jones8ede1a22011-10-05 13:34:52 -0500955certain parts of your queries for reuse at a later point in your
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000956script's execution. Normally, when an Query Builder call is completed,
Derek Jones8ede1a22011-10-05 13:34:52 -0500957all stored information is reset for the next call. With caching, you can
958prevent this reset, and reuse information easily.
959
960Cached calls are cumulative. If you make 2 cached select() calls, and
961then 2 uncached select() calls, this will result in 4 select() calls.
962There are three Caching functions available:
963
James L Parry42a7df62014-11-25 12:06:49 -0800964**$this->db->start_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500965
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000966This function must be called to begin caching. All Query Builder queries
Derek Jones8ede1a22011-10-05 13:34:52 -0500967of the correct type (see below for supported queries) are stored for
968later use.
969
James L Parry42a7df62014-11-25 12:06:49 -0800970**$this->db->stop_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500971
972This function can be called to stop caching.
973
James L Parry42a7df62014-11-25 12:06:49 -0800974**$this->db->flush_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500975
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000976This function deletes all items from the Query Builder cache.
Derek Jones8ede1a22011-10-05 13:34:52 -0500977
James L Parry42a7df62014-11-25 12:06:49 -0800978An example of caching
979---------------------
980
Derek Jones8ede1a22011-10-05 13:34:52 -0500981Here's a usage example::
982
983 $this->db->start_cache();
984 $this->db->select('field1');
985 $this->db->stop_cache();
986 $this->db->get('tablename');
987 //Generates: SELECT `field1` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +0100988
Derek Jones8ede1a22011-10-05 13:34:52 -0500989 $this->db->select('field2');
990 $this->db->get('tablename');
991 //Generates: SELECT `field1`, `field2` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +0100992
Derek Jones8ede1a22011-10-05 13:34:52 -0500993 $this->db->flush_cache();
994 $this->db->select('field2');
995 $this->db->get('tablename');
996 //Generates: SELECT `field2` FROM (`tablename`)
997
998
999.. note:: The following statements can be cached: select, from, join,
1000 where, like, group_by, having, order_by, set
1001
1002
James L Parry42a7df62014-11-25 12:06:49 -08001003***********************
1004Resetting Query Builder
1005***********************
1006
James L Parry141288d2014-12-06 01:45:12 -08001007**$this->db->reset_query()**
Kyle Farris48d8fb62011-10-14 17:59:49 -03001008
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001009Resetting Query Builder allows you to start fresh with your query without
WanWizard7219c072011-12-28 14:09:05 +01001010executing it first using a method like $this->db->get() or $this->db->insert().
1011Just like the methods that execute a query, this will *not* reset items you've
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001012cached using `Query Builder Caching`_.
Kyle Farris48d8fb62011-10-14 17:59:49 -03001013
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001014This is useful in situations where you are using Query Builder to generate SQL
WanWizard7219c072011-12-28 14:09:05 +01001015(ex. ``$this->db->get_compiled_select()``) but then choose to, for instance,
Kyle Farris48d8fb62011-10-14 17:59:49 -03001016run the query::
1017
1018 // Note that the second parameter of the get_compiled_select method is FALSE
1019 $sql = $this->db->select(array('field1','field2'))
1020 ->where('field3',5)
1021 ->get_compiled_select('mytable', FALSE);
1022
1023 // ...
1024 // Do something crazy with the SQL code... like add it to a cron script for
1025 // later execution or something...
1026 // ...
1027
1028 $data = $this->db->get()->result_array();
1029
1030 // Would execute and return an array of results of the following query:
Andrey Andreev896d3e32014-01-07 17:13:25 +02001031 // SELECT field1, field1 from mytable where field3 = 5;
1032
1033.. note:: Double calls to ``get_compiled_select()`` while you're using the
1034 Query Builder Caching functionality and NOT resetting your queries
1035 will results in the cache being merged twice. That in turn will
James L Parry73817112014-12-08 03:09:29 -08001036 i.e. if you're caching a ``select()`` - select the same field twice.
1037
1038***************
1039Class Reference
1040***************
1041
1042.. class:: CI_DB_query_builder
1043
1044 .. method:: count_all_results([$table = ''])
1045
1046 :param string $table: Table name to query
1047 :returns: Number of rows in the query result
1048 :rtype: int
1049
1050 Generates a platform-specific query string that counts
1051 all records returned by an Query Builder query.
1052
1053 .. method:: dbprefix([$table = ''])
1054
1055 :param string $table: The table name to work with
1056 :returns: The modified table name
1057 :rtype: string
1058
1059 Prepends a database prefix if one exists in configuration
1060
1061 .. method:: delete([$table = ''[, $where = ''[, $limit = NULL[, $reset_data = TRUE]]]])
1062
1063 :param mixed $table: The table(s) to delete from; string or array
1064 :param string $where: The where clause
1065 :param string $limit: The limit clause
1066 :param boolean $reset_data: TRUE to reset the query "write" clause
1067 :returns: DB_query_builder instance, FALSE on failure
1068 :rtype: mixed
1069
1070 Compiles a delete string and runs the query
1071
1072 .. method:: distinct([$val = TRUE])
1073
1074 :param boolean $val: Desired value of the "distinct" flag
1075 :returns: DB_query_driver instance
1076 :rtype: object
1077
1078 Sets a flag which tells the query string compiler to add DISTINCT
1079
1080 .. method:: empty_table([$table = ''])
1081
1082 :param string $table: Name of table to empty
1083 :returns: DB_driver instance
1084 :rtype: object
1085
1086 Compiles a delete string and runs "DELETE FROM table"
1087
1088 .. method:: flush_cache()
1089
1090 :rtype: void
1091
1092 Empties the QB cache
1093
1094 .. method:: from($from)
1095
1096 :param mixed $from: Can be a string or array
1097 :returns: DB_query_builder instance
1098 :rtype: object
1099
1100 Generates the FROM portion of the query
1101
1102 .. method:: get([$table = ''[, $limit = NULL[, $offset = NULL]]])
1103
1104 :param string $table: The table to query
1105 :param string $limit: The limit clause
1106 :param string $offset: The offset clause
1107 :returns: DB_result
1108 :rtype: object
1109
1110 Compiles the select statement based on the other functions
1111 called and runs the query
1112
1113 .. method:: get_compiled_delete([$table = ''[, $reset = TRUE]])
1114
1115 :param string $table: Name of the table to delete from
1116 :param boolean $reset: TRUE: reset QB values; FALSE: leave QB values alone
1117 :returns: The SQL string
1118 :rtype: string
1119
1120 Compiles a delete query string and returns the sql
1121
1122 .. method:: get_compiled_insert([$table = ''[, $reset = TRUE]])
1123
1124 :param string $table: Name of the table to insert into
1125 :param boolean $reset: TRUE: reset QB values; FALSE: leave QB values alone
1126 :returns: The SQL string
1127 :rtype: string
1128
1129 Compiles an insert query string and returns the sql
1130
1131 .. method:: get_compiled_select([$table = ''[, $reset = TRUE]])
1132
1133 :param string $table: Name of the table to select from
1134 :param boolean $reset: TRUE: reset QB values; FALSE: leave QB values alone
1135 :returns: The SQL string
1136 :rtype: string
1137
1138 Compiles a select query string and returns the sql
1139
1140 .. method:: get_compiled_update([$table = ''[, $reset = TRUE]])
1141
1142 :param string $table: Name of the table to update
1143 :param boolean $reset: TRUE: reset QB values; FALSE: leave QB values alone
1144 :returns: The SQL string
1145 :rtype: string
1146
1147 Compiles an update query string and returns the sql
1148
1149 .. method:: get_where([$table = ''[, $where = NULL[, $limit = NULL[, $offset = NULL]]]])
1150
1151 :param mixed $table: The table(s) to delete from; string or array
1152 :param string $where: The where clause
1153 :param int $limit: Number of records to return
1154 :param int $offset: Number of records to skip
1155 :returns: DB_result
1156 :rtype: object
1157
1158 Allows the where clause, limit and offset to be added directly
1159
1160 .. method:: group_by($by[, $escape = NULL])
1161
1162 :param mixed $by: Field(s) to group by; string or array
1163 :returns: DB_query_builder instance
1164 :rtype: object
1165
1166 Adds a GROUPBY clause to the query
1167
1168 .. method:: group_end()
1169
1170 :returns: DB_query_builder instance
1171 :rtype: object
1172
1173 Ends a query group
1174
1175 .. method:: group_start([$not = ''[, $type = 'AND ']])
1176
1177 :param string $not: (Internal use only)
1178 :param string $type: (Internal use only)
1179 :returns: DB_query_builder instance
1180 :rtype: object
1181
1182 Starts a query group.
1183
1184 .. method:: having($key[, $value = NULL[, $escape = NULL]])
1185
1186 :param string $key: Key (string) or associative array of values
1187 :param string $value: Value sought if the key is a string
1188 :param string $escape: TRUE to escape the content
1189 :returns: DB_query_builder instance
1190 :rtype: object
1191
1192 Separates multiple calls with 'AND'.
1193
1194 .. method:: insert([$table = ''[, $set = NULL[, $escape = NULL]]])
1195
1196 :param string $table: The table to insert data into
1197 :param array $set: An associative array of insert values
1198 :param boolean $table: Whether to escape values and identifiers
1199 :returns: DB_result
1200 :rtype: object
1201
1202 Compiles an insert string and runs the query
1203
1204 .. method:: insert_batch([$table = ''[, $set = NULL[, $escape = NULL]]])
1205
1206 :param string $table: The table to insert data into
1207 :param array $set: An associative array of insert values
1208 :param boolean $escape: Whether to escape values and identifiers
1209 :returns: Number of rows inserted or FALSE on failure
1210 :rtype: mixed
1211
1212 Compiles batch insert strings and runs the queries
1213
1214 .. method:: join($table, $cond[, $type = ''[, $escape = NULL]])
1215
1216 :param string $table: Name of the table being joined
1217 :param string $cond: The JOIN condition
1218 :param string $type: The JOIN type
1219 :param boolean $escape: Whether to escape values and identifiers
1220 :returns: DB_query_builder instance
1221 :rtype: object
1222
1223 Generates the JOIN portion of the query
1224
1225 .. method:: like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1226
1227 :param string $field: Name of field to compare
1228 :param string $match: Text portion to match
1229 :param string $side: Position of a match
1230 :param boolean $escape: Whether to escape values and identifiers
1231 :returns: DB_query_builder instance
1232 :rtype: object
1233
1234 Generates a %LIKE% portion of the query.
1235 Separates multiple calls with 'AND'.
1236
1237 .. method:: limit($value[, $offset = FALSE])
1238
1239 :param mixed $value: Number of rows to limit the results to, NULL for no limit
1240 :param mixed $offset: Number of rows to skip, FALSE if no offset used
1241 :returns: DB_query_builder instance
1242 :rtype: object
1243
1244 Specify a limit and offset for the query
1245
1246 .. method:: not_group_start()
1247
1248 :returns: DB_query_builder instance
1249 :rtype: object
1250
1251 Starts a query group, but NOTs the group
1252
1253 .. method:: not_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1254
1255 :param string $field: Name of field to compare
1256 :param string $match: Text portion to match
1257 :param string $side: Position of a match
1258 :param boolean $escape: Whether to escape values and identifiers
1259 :returns: DB_query_builder instance
1260 :rtype: object
1261
1262 Generates a NOT LIKE portion of the query.
1263 Separates multiple calls with 'AND'.
1264
1265 .. method:: offset($offset)
1266
1267 :param int $offset: Number of rows to skip in a query
1268 :returns: DB_query_builder instance
1269 :rtype: object
1270
1271 Sets the OFFSET value
1272
1273 .. method:: or_group_start()
1274
1275 :returns: DB_query_builder instance
1276 :rtype: object
1277
1278 Starts a query group, but ORs the group
1279
1280 .. method:: or_having($key[, $value = NULL[, $escape = NULL]])
1281
1282 :param string $key: Key (string) or associative array of values
1283 :param string $value: Value sought if the key is a string
1284 :param string $escape: TRUE to escape the content
1285 :returns: DB_query_builder instance
1286 :rtype: object
1287
1288 Separates multiple calls with 'OR'.
1289
1290 .. method:: or_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1291
1292 :param string $field: Name of field to compare
1293 :param string $match: Text portion to match
1294 :param string $side: Position of a match
1295 :param boolean $escape: Whether to escape values and identifiers
1296 :returns: DB_query_builder instance
1297 :rtype: object
1298
1299 Generates a %LIKE% portion of the query.
1300 Separates multiple calls with 'OR'.
1301
1302 .. method:: or_not_group_start()
1303
1304 :returns: DB_query_builder instance
1305 :rtype: object
1306
1307 Starts a query group, but OR NOTs the group
1308
1309 .. method:: or_not_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1310
1311 :param string $field: Name of field to compare
1312 :param string $match: Text portion to match
1313 :param string $side: Position of a match
1314 :param boolean $escape: Whether to escape values and identifiers
1315 :returns: DB_query_builder instance
1316 :rtype: object
1317
1318 Generates a NOT LIKE portion of the query.
1319 Separates multiple calls with 'OR'.
1320
1321 .. method:: or_where($key[, $value = NULL[, $escape = NULL]])
1322
1323 :param mixed $key: Name of field to compare, or associative array
1324 :param mixed $value: If a single key, compared to this value
1325 :param boolean $escape: Whether to escape values and identifiers
1326 :returns: DB_query_builder instance
1327 :rtype: object
1328
1329 Generates the WHERE portion of the query.
1330 Separates multiple calls with 'OR'.
1331
1332 .. method:: or_where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1333
1334 :param string $key: The field to search
1335 :param array $values: The values searched on
1336 :param boolean $escape: Whether to escape values and identifiers
1337 :returns: DB_query_builder instance
1338 :rtype: object
1339
1340 Generates a WHERE field IN('item', 'item') SQL query,
1341 joined with 'OR' if appropriate.
1342
1343 .. method:: or_where_not_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1344
1345 :param string $key: The field to search
1346 :param array $values: The values searched on
1347 :param boolean $escape: Whether to escape values and identifiers
1348 :returns: DB_query_builder instance
1349 :rtype: object
1350
1351 Generates a WHERE field NOT IN('item', 'item') SQL query,
1352 joined with 'OR' if appropriate.
1353
1354 .. method:: order_by($orderby[, $direction = ''[, $escape = NULL]])
1355
1356 :param string $orderby: The field to order by
1357 :param string $direction: The order requested - asc, desc or random
1358 :param boolean $escape: Whether to escape values and identifiers
1359 :returns: DB_query_builder instance
1360 :rtype: object
1361
1362 Generates an ORDER BY clause in the SQL query
1363
1364 .. method:: replace([$table = ''[, $set = NULL]])
1365
1366 :param string $table: The table to query
1367 :param array $set: Associative array of insert values
1368 :returns: DB_result, FALSE on failure
1369 :rtype: mixed
1370
1371 Compiles an replace into string and runs the query
1372
1373 .. method:: reset_query()
1374
1375 :rtype: void
1376
1377 Publicly-visible method to reset the QB values.
1378
1379 .. method:: select([$select = '*'[, $escape = NULL]])
1380
1381 :param string $select: Comma-separated list of fields to select
1382 :param boolean $escape: Whether to escape values and identifiers
1383 :returns: DB_query_builder instance
1384 :rtype: object
1385
1386 Generates the SELECT portion of the query
1387
1388 .. method:: select_avg([$select = ''[, $alias = '']])
1389
1390 :param string $select: Field to compute the average of
1391 :param string $alias: Alias for the resulting value
1392 :returns: DB_query_builder instance
1393 :rtype: object
1394
1395 Generates a SELECT AVG(field) portion of a query
1396
1397 .. method:: select_max([$select = ''[, $alias = '']])
1398
1399 :param string $select: Field to compute the maximum of
1400 :param string $alias: Alias for the resulting value
1401 :returns: DB_query_builder instance
1402 :rtype: object
1403
1404 Generates a SELECT MAX(field) portion of a query
1405
1406 .. method:: select_min([$select = ''[, $alias = '']])
1407
1408 :param string $select: Field to compute the minimum of
1409 :param string $alias: Alias for the resulting value
1410 :returns: DB_query_builder instance
1411 :rtype: object
1412
1413 Generates a SELECT MIN(field) portion of a query
1414
1415 .. method:: select_sum([$select = ''[, $alias = '']])
1416
1417 :param string $select: Field to compute the sum of
1418 :param string $alias: Alias for the resulting value
1419 :returns: DB_query_builder instance
1420 :rtype: object
1421
1422 Generates a SELECT SUM(field) portion of a query
1423
1424 .. method:: set($key[, $value = ''[, $escape = NULL]])
1425
1426 :param mixed $key: The field to be set, or an array of key/value pairs
1427 :param string $value: If a single key, its new value
1428 :param boolean $escape: Whether to escape values and identifiers
1429 :returns: DB_query_builder instance
1430 :rtype: object
1431
1432 Allows key/value pairs to be set for inserting or updating
1433
1434 .. method:: set_dbprefix([$prefix = ''])
1435
1436 :param string $prefix: The new prefix to use
1437 :returns: The DB prefix in use
1438 :rtype: string
1439
1440 Set's the DB Prefix to something new without needing to reconnect
1441
1442 .. method:: set_insert_batch($key[, $value = ''[, $escape = NULL]])
1443
1444 :param mixed $key: The field to be set, or an array of key/value pairs
1445 :param string $value: If a single key, its new value
1446 :param boolean $escape: Whether to escape values and identifiers
1447 :returns: DB_query_builder instance
1448 :rtype: object
1449
1450 The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
1451
1452 .. method:: set_update_batch($key[, $value = ''[, $escape = NULL]])
1453
1454 :param mixed $key: The field to be set, or an array of key/value pairs
1455 :param string $value: If a single key, its new value
1456 :param boolean $escape: Whether to escape values and identifiers
1457 :returns: DB_query_builder instance
1458 :rtype: object
1459
1460 The "set_batch_batch" function. Allows key/value pairs to be set for batch batch
1461
1462 .. method:: start_cache()
1463
1464 :rtype: void
1465
1466 Start DB caching
1467
1468 .. method:: stop_cache()
1469
1470 :rtype: void
1471
1472 Stop DB caching
1473
1474 .. method:: truncate([$table = ''])
1475
1476 :param string $table: Name fo the table to truncate
1477 :returns: DB_result
1478 :rtype: object
1479
1480 Compiles a truncate string and runs the query.
1481 If the database does not support the truncate() command
1482 This function maps to "DELETE FROM table"
1483
1484 .. method:: update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]])
1485
1486 :param string $table: The table to insert data into
1487 :param array $set: An associative array of insert values
1488 :param string $where: WHERE clause to use
1489 :param string $limit: LIMIT clause to use
1490 :returns: DB_result
1491 :rtype: object
1492
1493 Compiles an update string and runs the query.
1494
1495 .. method:: update_batch([$table = ''[, $set = NULL[, $value = NULL]]])
1496
1497 :param string $table: The table to update data in
1498 :param mixed $set: The field to be set, or an array of key/value pairs
1499 :param string $value: If a single key, its new value
1500 :returns: DB_result
1501 :rtype: object
1502
1503 Compiles an update string and runs the query.
1504
1505 .. method:: where($key[, $value = NULL[, $escape = NULL]])
1506
1507 :param mixed $key: Name of field to compare, or associative array
1508 :param mixed $value: If a single key, compared to this value
1509 :param boolean $escape: Whether to escape values and identifiers
1510 :returns: DB_query_builder instance
1511 :rtype: object
1512
1513 Generates the WHERE portion of the query.
1514 Separates multiple calls with 'AND'.
1515
1516 .. method:: where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1517
1518 :param string $key: Name of field to examine
1519 :param array $values: Array of target values
1520 :param boolean $escape: Whether to escape values and identifiers
1521 :returns: DB_query_builder instance
1522 :rtype: object
1523
1524 Generates a WHERE field IN('item', 'item') SQL query,
1525 joined with 'AND' if appropriate.
1526
1527 .. method:: where_not_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1528
1529 :param string $key: Name of field to examine
1530 :param array $values: Array of target values
1531 :param boolean $escape: Whether to escape values and identifiers
1532 :returns: DB_query_builder instance
1533 :rtype: object
1534
1535 Generates a WHERE field NOT IN('item', 'item') SQL query,
1536 joined with 'AND' if appropriate.