blob: b06396e964b600446d684c8ec94e82bde83fac8f [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
David Wosnitzad31a4e62014-12-12 16:35:35 +01005CodeIgniter gives you access to a Query Builder class. This pattern
6allows information to be retrieved, inserted, and updated in your
Jamie Rumbelow7efad202012-02-19 12:37:00 +00007database 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);
Andrey Andreev4fce5c42014-12-11 17:11:48 +020043
44 // Executes: SELECT * FROM mytable LIMIT 20, 10
45 // (in MySQL. Other databases have slightly different syntax)
Derek Jones8ede1a22011-10-05 13:34:52 -050046
47You'll notice that the above function is assigned to a variable named
48$query, which can be used to show the results::
49
50 $query = $this->db->get('mytable');
WanWizard7219c072011-12-28 14:09:05 +010051
Derek Jones8ede1a22011-10-05 13:34:52 -050052 foreach ($query->result() as $row)
53 {
54 echo $row->title;
55 }
56
57Please visit the :doc:`result functions <results>` page for a full
58discussion regarding result generation.
59
James L Parry141288d2014-12-06 01:45:12 -080060**$this->db->get_compiled_select()**
James L Parry42a7df62014-11-25 12:06:49 -080061
62Compiles the selection query just like **$this->db->get()** but does not *run*
Kyle Farris48d8fb62011-10-14 17:59:49 -030063the query. This method simply returns the SQL query as a string.
64
65Example::
66
67 $sql = $this->db->get_compiled_select('mytable');
68 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +010069
Andrey Andreev4fce5c42014-12-11 17:11:48 +020070 // Prints string: SELECT * FROM mytable
WanWizard7219c072011-12-28 14:09:05 +010071
Jamie Rumbelow7efad202012-02-19 12:37:00 +000072The second parameter enables you to set whether or not the query builder query
GDmac01e9fb12013-11-09 08:01:52 +010073will be reset (by default it will be reset, just like when using `$this->db->get()`)::
Kyle Farris48d8fb62011-10-14 17:59:49 -030074
75 echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);
Andrey Andreev4fce5c42014-12-11 17:11:48 +020076
77 // Prints string: SELECT * FROM mytable LIMIT 20, 10
Kyle Farris48d8fb62011-10-14 17:59:49 -030078 // (in MySQL. Other databases have slightly different syntax)
WanWizard7219c072011-12-28 14:09:05 +010079
Kyle Farris48d8fb62011-10-14 17:59:49 -030080 echo $this->db->select('title, content, date')->get_compiled_select();
81
Andrey Andreev4fce5c42014-12-11 17:11:48 +020082 // Prints string: SELECT title, content, date FROM mytable LIMIT 20, 10
WanWizard7219c072011-12-28 14:09:05 +010083
84The key thing to notice in the above example is that the second query did not
James L Parry42a7df62014-11-25 12:06:49 -080085utilize **$this->db->from()** and did not pass a table name into the first
WanWizard7219c072011-12-28 14:09:05 +010086parameter. The reason for this outcome is because the query has not been
James L Parry42a7df62014-11-25 12:06:49 -080087executed using **$this->db->get()** which resets values or reset directly
88using **$this->db->reset_query()**.
Kyle Farris48d8fb62011-10-14 17:59:49 -030089
James L Parry141288d2014-12-06 01:45:12 -080090**$this->db->get_where()**
Derek Jones8ede1a22011-10-05 13:34:52 -050091
92Identical to the above function except that it permits you to add a
93"where" clause in the second parameter, instead of using the db->where()
94function::
95
96 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
97
98Please read the about the where function below for more information.
99
Greg Akerffd24a42011-12-25 22:27:59 -0600100.. note:: get_where() was formerly known as getwhere(), which has been removed
Derek Jones8ede1a22011-10-05 13:34:52 -0500101
James L Parry141288d2014-12-06 01:45:12 -0800102**$this->db->select()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500103
104Permits you to write the SELECT portion of your query::
105
106 $this->db->select('title, content, date');
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200107 $query = $this->db->get('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500108
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200109 // Executes: SELECT title, content, date FROM mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500110
111.. note:: If you are selecting all (\*) from a table you do not need to
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200112 use this function. When omitted, CodeIgniter assumes that you wish
David Wosnitzad31a4e62014-12-12 16:35:35 +0100113 to select all fields and automatically adds 'SELECT \*'.
Derek Jones8ede1a22011-10-05 13:34:52 -0500114
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200115``$this->db->select()`` accepts an optional second parameter. If you set it
David Wosnitzad31a4e62014-12-12 16:35:35 +0100116to FALSE, CodeIgniter will not try to protect your field or table names.
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200117This is useful if you need a compound select statement where automatic
118escaping of fields may break them.
Derek Jones8ede1a22011-10-05 13:34:52 -0500119
120::
121
WanWizard7219c072011-12-28 14:09:05 +0100122 $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 -0500123 $query = $this->db->get('mytable');
124
James L Parry141288d2014-12-06 01:45:12 -0800125**$this->db->select_max()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500126
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200127Writes a ``SELECT MAX(field)`` portion for your query. You can optionally
Derek Jones8ede1a22011-10-05 13:34:52 -0500128include a second parameter to rename the resulting field.
129
130::
131
132 $this->db->select_max('age');
133 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members
WanWizard7219c072011-12-28 14:09:05 +0100134
Derek Jones8ede1a22011-10-05 13:34:52 -0500135 $this->db->select_max('age', 'member_age');
136 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members
137
138
James L Parry42a7df62014-11-25 12:06:49 -0800139**$this->db->select_min()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500140
141Writes a "SELECT MIN(field)" portion for your query. As with
142select_max(), You can optionally include a second parameter to rename
143the resulting field.
144
145::
146
147 $this->db->select_min('age');
148 $query = $this->db->get('members'); // Produces: SELECT MIN(age) as age FROM members
149
150
James L Parry42a7df62014-11-25 12:06:49 -0800151**$this->db->select_avg()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500152
153Writes a "SELECT AVG(field)" portion for your query. As with
154select_max(), You can optionally include a second parameter to rename
155the resulting field.
156
157::
158
159 $this->db->select_avg('age');
160 $query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
161
162
James L Parry42a7df62014-11-25 12:06:49 -0800163**$this->db->select_sum()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500164
165Writes a "SELECT SUM(field)" portion for your query. As with
166select_max(), You can optionally include a second parameter to rename
167the resulting field.
168
169::
170
171 $this->db->select_sum('age');
172 $query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members
173
James L Parry141288d2014-12-06 01:45:12 -0800174**$this->db->from()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500175
176Permits you to write the FROM portion of your query::
177
178 $this->db->select('title, content, date');
179 $this->db->from('mytable');
180 $query = $this->db->get(); // Produces: SELECT title, content, date FROM mytable
181
182.. note:: As shown earlier, the FROM portion of your query can be specified
183 in the $this->db->get() function, so use whichever method you prefer.
184
James L Parry141288d2014-12-06 01:45:12 -0800185**$this->db->join()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500186
187Permits you to write the JOIN portion of your query::
188
189 $this->db->select('*');
190 $this->db->from('blogs');
191 $this->db->join('comments', 'comments.id = blogs.id');
192 $query = $this->db->get();
WanWizard7219c072011-12-28 14:09:05 +0100193
Derek Jones8ede1a22011-10-05 13:34:52 -0500194 // Produces:
kenjisc35d2c92011-10-26 17:09:17 +0900195 // SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Derek Jones8ede1a22011-10-05 13:34:52 -0500196
197Multiple function calls can be made if you need several joins in one
198query.
199
200If you need a specific type of JOIN you can specify it via the third
201parameter of the function. Options are: left, right, outer, inner, left
202outer, and right outer.
203
204::
205
206 $this->db->join('comments', 'comments.id = blogs.id', 'left');
207 // Produces: LEFT JOIN comments ON comments.id = blogs.id
208
James L Parry42a7df62014-11-25 12:06:49 -0800209*************************
210Looking for Specific Data
211*************************
212
James L Parry141288d2014-12-06 01:45:12 -0800213**$this->db->where()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500214
215This function enables you to set **WHERE** clauses using one of four
216methods:
217
218.. note:: All values passed to this function are escaped automatically,
219 producing safer queries.
220
221#. **Simple key/value method:**
222
223 ::
224
WanWizard7219c072011-12-28 14:09:05 +0100225 $this->db->where('name', $name); // Produces: WHERE name = 'Joe'
Derek Jones8ede1a22011-10-05 13:34:52 -0500226
227 Notice that the equal sign is added for you.
228
229 If you use multiple function calls they will be chained together with
230 AND between them:
231
232 ::
233
234 $this->db->where('name', $name);
235 $this->db->where('title', $title);
236 $this->db->where('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100237 // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500238
239#. **Custom key/value method:**
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200240
Derek Jones8ede1a22011-10-05 13:34:52 -0500241 You can include an operator in the first parameter in order to
242 control the comparison:
243
244 ::
245
246 $this->db->where('name !=', $name);
WanWizard7219c072011-12-28 14:09:05 +0100247 $this->db->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500248
249#. **Associative array method:**
250
251 ::
252
253 $array = array('name' => $name, 'title' => $title, 'status' => $status);
254 $this->db->where($array);
WanWizard7219c072011-12-28 14:09:05 +0100255 // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500256
257 You can include your own operators using this method as well:
258
259 ::
260
261 $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
262 $this->db->where($array);
263
264#. **Custom string:**
265 You can write your own clauses manually::
266
267 $where = "name='Joe' AND status='boss' OR status='active'";
268 $this->db->where($where);
269
270
Andrey Andreev4fce5c42014-12-11 17:11:48 +0200271``$this->db->where()`` accepts an optional third parameter. If you set it to
272FALSE, CodeIgniter will not try to protect your field or table names.
Derek Jones8ede1a22011-10-05 13:34:52 -0500273
274::
275
276 $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
277
James L Parry42a7df62014-11-25 12:06:49 -0800278**$this->db->or_where()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500279
280This function is identical to the one above, except that multiple
281instances are joined by OR::
282
283 $this->db->where('name !=', $name);
284 $this->db->or_where('id >', $id); // Produces: WHERE name != 'Joe' OR id > 50
285
286.. note:: or_where() was formerly known as orwhere(), which has been
287 removed.
288
James L Parry141288d2014-12-06 01:45:12 -0800289**$this->db->where_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500290
291Generates a WHERE field IN ('item', 'item') SQL query joined with AND if
292appropriate
293
294::
295
296 $names = array('Frank', 'Todd', 'James');
297 $this->db->where_in('username', $names);
298 // Produces: WHERE username IN ('Frank', 'Todd', 'James')
299
300
James L Parry42a7df62014-11-25 12:06:49 -0800301**$this->db->or_where_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500302
303Generates a WHERE field IN ('item', 'item') SQL query joined with OR if
304appropriate
305
306::
307
308 $names = array('Frank', 'Todd', 'James');
309 $this->db->or_where_in('username', $names);
310 // Produces: OR username IN ('Frank', 'Todd', 'James')
311
James L Parry141288d2014-12-06 01:45:12 -0800312**$this->db->where_not_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500313
314Generates a WHERE field NOT IN ('item', 'item') SQL query joined with
315AND if appropriate
316
317::
318
319 $names = array('Frank', 'Todd', 'James');
320 $this->db->where_not_in('username', $names);
321 // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')
322
323
James L Parry42a7df62014-11-25 12:06:49 -0800324**$this->db->or_where_not_in()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500325
326Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR
327if appropriate
328
329::
330
331 $names = array('Frank', 'Todd', 'James');
332 $this->db->or_where_not_in('username', $names);
333 // Produces: OR username NOT IN ('Frank', 'Todd', 'James')
334
James L Parry42a7df62014-11-25 12:06:49 -0800335************************
336Looking for Similar Data
337************************
Derek Jones8ede1a22011-10-05 13:34:52 -0500338
James L Parry141288d2014-12-06 01:45:12 -0800339**$this->db->like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500340
Andrey Andreev41738232012-11-30 00:13:17 +0200341This method enables you to generate **LIKE** clauses, useful for doing
Derek Jones8ede1a22011-10-05 13:34:52 -0500342searches.
343
Andrey Andreev41738232012-11-30 00:13:17 +0200344.. note:: All values passed to this method are escaped automatically.
Derek Jones8ede1a22011-10-05 13:34:52 -0500345
346#. **Simple key/value method:**
347
348 ::
349
Andrey Andreev41738232012-11-30 00:13:17 +0200350 $this->db->like('title', 'match');
351 // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500352
Andrey Andreev41738232012-11-30 00:13:17 +0200353 If you use multiple method calls they will be chained together with
Derek Jones8ede1a22011-10-05 13:34:52 -0500354 AND between them::
355
356 $this->db->like('title', 'match');
357 $this->db->like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200358 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500359
360 If you want to control where the wildcard (%) is placed, you can use
361 an optional third argument. Your options are 'before', 'after' and
362 'both' (which is the default).
363
364 ::
365
Andrey Andreev41738232012-11-30 00:13:17 +0200366 $this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
367 $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
368 $this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500369
370#. **Associative array method:**
371
372 ::
373
374 $array = array('title' => $match, 'page1' => $match, 'page2' => $match);
375 $this->db->like($array);
Andrey Andreev41738232012-11-30 00:13:17 +0200376 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500377
378
James L Parry42a7df62014-11-25 12:06:49 -0800379**$this->db->or_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500380
Andrey Andreev41738232012-11-30 00:13:17 +0200381This method is identical to the one above, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500382instances are joined by OR::
383
384 $this->db->like('title', 'match'); $this->db->or_like('body', $match);
Andrey Andreev41738232012-11-30 00:13:17 +0200385 // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500386
Andrey Andreev41738232012-11-30 00:13:17 +0200387.. note:: ``or_like()`` was formerly known as ``orlike()``, which has been removed.
Derek Jones8ede1a22011-10-05 13:34:52 -0500388
James L Parry42a7df62014-11-25 12:06:49 -0800389**$this->db->not_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500390
Andrey Andreev41738232012-11-30 00:13:17 +0200391This method is identical to ``like()``, except that it generates
392NOT LIKE statements::
Derek Jones8ede1a22011-10-05 13:34:52 -0500393
Andrey Andreev41738232012-11-30 00:13:17 +0200394 $this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500395
James L Parry42a7df62014-11-25 12:06:49 -0800396**$this->db->or_not_like()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500397
Andrey Andreev41738232012-11-30 00:13:17 +0200398This method is identical to ``not_like()``, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500399instances are joined by OR::
400
401 $this->db->like('title', 'match');
402 $this->db->or_not_like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200403 // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500404
James L Parry141288d2014-12-06 01:45:12 -0800405**$this->db->group_by()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500406
407Permits you to write the GROUP BY portion of your query::
408
409 $this->db->group_by("title"); // Produces: GROUP BY title
410
411You can also pass an array of multiple values as well::
412
413 $this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
414
415.. note:: group_by() was formerly known as groupby(), which has been
416 removed.
417
James L Parry141288d2014-12-06 01:45:12 -0800418**$this->db->distinct()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500419
420Adds the "DISTINCT" keyword to a query
421
422::
423
424 $this->db->distinct();
425 $this->db->get('table'); // Produces: SELECT DISTINCT * FROM table
426
James L Parry141288d2014-12-06 01:45:12 -0800427**$this->db->having()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500428
429Permits you to write the HAVING portion of your query. There are 2
430possible syntaxes, 1 argument or 2::
431
432 $this->db->having('user_id = 45'); // Produces: HAVING user_id = 45
WanWizard7219c072011-12-28 14:09:05 +0100433 $this->db->having('user_id', 45); // Produces: HAVING user_id = 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500434
435You can also pass an array of multiple values as well::
436
437 $this->db->having(array('title =' => 'My Title', 'id <' => $id));
438 // Produces: HAVING title = 'My Title', id < 45
439
440
441If you are using a database that CodeIgniter escapes queries for, you
442can prevent escaping content by passing an optional third argument, and
443setting it to FALSE.
444
445::
446
447 $this->db->having('user_id', 45); // Produces: HAVING `user_id` = 45 in some databases such as MySQL
448 $this->db->having('user_id', 45, FALSE); // Produces: HAVING user_id = 45
449
450
James L Parry42a7df62014-11-25 12:06:49 -0800451**$this->db->or_having()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500452
453Identical to having(), only separates multiple clauses with "OR".
454
James L Parry42a7df62014-11-25 12:06:49 -0800455****************
456Ordering results
457****************
458
James L Parry141288d2014-12-06 01:45:12 -0800459**$this->db->order_by()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500460
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200461Lets you set an ORDER BY clause.
462
463The first parameter contains the name of the column you would like to order by.
464
465The second parameter lets you set the direction of the result.
466Options are **ASC**, **DESC** AND **RANDOM**.
Derek Jones8ede1a22011-10-05 13:34:52 -0500467
468::
469
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200470 $this->db->order_by('title', 'DESC');
471 // Produces: ORDER BY `title` DESC
Derek Jones8ede1a22011-10-05 13:34:52 -0500472
473You can also pass your own string in the first parameter::
474
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200475 $this->db->order_by('title DESC, name ASC');
476 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500477
478Or multiple function calls can be made if you need multiple fields.
479
480::
481
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200482 $this->db->order_by('title', 'DESC');
483 $this->db->order_by('name', 'ASC');
484 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500485
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200486If you choose the **RANDOM** direction option, then the first parameters will
487be ignored, unless you specify a numeric seed value.
488
489::
490
491 $this->db->order_by('title', 'RANDOM');
492 // Produces: ORDER BY RAND()
493
494 $this->db->order_by(42, 'RANDOM');
495 // Produces: ORDER BY RAND(42)
Derek Jones8ede1a22011-10-05 13:34:52 -0500496
497.. note:: order_by() was formerly known as orderby(), which has been
498 removed.
499
Andrey Andreev0dfb62f2012-10-30 11:37:15 +0200500.. note:: Random ordering is not currently supported in Oracle and
501 will default to ASC instead.
Derek Jones8ede1a22011-10-05 13:34:52 -0500502
James L Parry42a7df62014-11-25 12:06:49 -0800503****************************
504Limiting or Counting Results
505****************************
506
James L Parry141288d2014-12-06 01:45:12 -0800507**$this->db->limit()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500508
509Lets you limit the number of rows you would like returned by the query::
510
511 $this->db->limit(10); // Produces: LIMIT 10
512
513The second parameter lets you set a result offset.
514
515::
516
517 $this->db->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
518
James L Parry141288d2014-12-06 01:45:12 -0800519**$this->db->count_all_results()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500520
521Permits you to determine the number of rows in a particular Active
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000522Record query. Queries will accept Query Builder restrictors such as
Derek Jones8ede1a22011-10-05 13:34:52 -0500523where(), or_where(), like(), or_like(), etc. Example::
524
525 echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
526 $this->db->like('title', 'match');
527 $this->db->from('my_table');
WanWizard7219c072011-12-28 14:09:05 +0100528 echo $this->db->count_all_results(); // Produces an integer, like 17
Derek Jones8ede1a22011-10-05 13:34:52 -0500529
James L Parry141288d2014-12-06 01:45:12 -0800530**$this->db->count_all()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500531
532Permits you to determine the number of rows in a particular table.
533Submit the table name in the first parameter. Example::
534
535 echo $this->db->count_all('my_table'); // Produces an integer, like 25
536
537**************
WanWizard7219c072011-12-28 14:09:05 +0100538Query grouping
539**************
540
541Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow
Timothy Warrene464b392012-03-13 14:09:31 -0400542you to create queries with complex WHERE clauses. Nested groups are supported. Example::
WanWizard7219c072011-12-28 14:09:05 +0100543
544 $this->db->select('*')->from('my_table')
545 ->group_start()
546 ->where('a', 'a')
547 ->or_group_start()
548 ->where('b', 'b')
549 ->where('c', 'c')
550 ->group_end()
551 ->group_end()
552 ->where('d', 'd')
553 ->get();
554
555 // Generates:
556 // SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
557
558.. note:: groups need to be balanced, make sure every group_start() is matched by a group_end().
559
James L Parry42a7df62014-11-25 12:06:49 -0800560**$this->db->group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100561
562Starts a new group by adding an opening parenthesis to the WHERE clause of the query.
563
James L Parry42a7df62014-11-25 12:06:49 -0800564**$this->db->or_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100565
566Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR'.
567
James L Parry42a7df62014-11-25 12:06:49 -0800568**$this->db->not_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100569
570Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'NOT'.
571
James L Parry42a7df62014-11-25 12:06:49 -0800572**$this->db->or_not_group_start()**
WanWizard7219c072011-12-28 14:09:05 +0100573
574Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR NOT'.
575
James L Parry42a7df62014-11-25 12:06:49 -0800576**$this->db->group_end()**
WanWizard7219c072011-12-28 14:09:05 +0100577
578Ends the current group by adding an closing parenthesis to the WHERE clause of the query.
579
580**************
Derek Jones8ede1a22011-10-05 13:34:52 -0500581Inserting Data
582**************
583
James L Parry141288d2014-12-06 01:45:12 -0800584**$this->db->insert()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500585
586Generates an insert string based on the data you supply, and runs the
587query. You can either pass an **array** or an **object** to the
588function. Here is an example using an array::
589
590 $data = array(
591 'title' => 'My title',
592 'name' => 'My Name',
593 'date' => 'My date'
594 );
WanWizard7219c072011-12-28 14:09:05 +0100595
Derek Jones8ede1a22011-10-05 13:34:52 -0500596 $this->db->insert('mytable', $data);
597 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
598
599The first parameter will contain the table name, the second is an
600associative array of values.
601
602Here is an example using an object::
603
604 /*
605 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200606 public $title = 'My Title';
607 public $content = 'My Content';
608 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500609 }
610 */
WanWizard7219c072011-12-28 14:09:05 +0100611
Derek Jones8ede1a22011-10-05 13:34:52 -0500612 $object = new Myclass;
613 $this->db->insert('mytable', $object);
614 // Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
615
616The first parameter will contain the table name, the second is an
617object.
618
619.. note:: All values are escaped automatically producing safer queries.
620
James L Parry141288d2014-12-06 01:45:12 -0800621**$this->db->get_compiled_insert()**
James L Parry42a7df62014-11-25 12:06:49 -0800622
James L Parry141288d2014-12-06 01:45:12 -0800623Compiles the insertion query just like $this->db->insert() but does not
Kyle Farris48d8fb62011-10-14 17:59:49 -0300624*run* the query. This method simply returns the SQL query as a string.
625
626Example::
627
628 $data = array(
629 'title' => 'My title',
630 'name' => 'My Name',
631 'date' => 'My date'
632 );
WanWizard7219c072011-12-28 14:09:05 +0100633
Kyle Farris48d8fb62011-10-14 17:59:49 -0300634 $sql = $this->db->set($data)->get_compiled_insert('mytable');
635 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +0100636
Kyle Farris48d8fb62011-10-14 17:59:49 -0300637 // Produces string: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
638
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000639The second parameter enables you to set whether or not the query builder query
James L Parry141288d2014-12-06 01:45:12 -0800640will be reset (by default it will be--just like $this->db->insert())::
WanWizard7219c072011-12-28 14:09:05 +0100641
Kyle Farris48d8fb62011-10-14 17:59:49 -0300642 echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);
WanWizard7219c072011-12-28 14:09:05 +0100643
Kyle Farris48d8fb62011-10-14 17:59:49 -0300644 // Produces string: INSERT INTO mytable (title) VALUES ('My Title')
WanWizard7219c072011-12-28 14:09:05 +0100645
Kyle Farris48d8fb62011-10-14 17:59:49 -0300646 echo $this->db->set('content', 'My Content')->get_compiled_insert();
647
648 // Produces string: INSERT INTO mytable (title, content) VALUES ('My Title', 'My Content')
WanWizard7219c072011-12-28 14:09:05 +0100649
650The key thing to notice in the above example is that the second query did not
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200651utlize `$this->db->from()` nor did it pass a table name into the first
WanWizard7219c072011-12-28 14:09:05 +0100652parameter. The reason this worked is because the query has not been executed
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200653using `$this->db->insert()` which resets values or reset directly using
654`$this->db->reset_query()`.
655
656.. note:: This method doesn't work for batched inserts.
Kyle Farris48d8fb62011-10-14 17:59:49 -0300657
James L Parry141288d2014-12-06 01:45:12 -0800658**$this->db->insert_batch()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500659
660Generates an insert string based on the data you supply, and runs the
661query. You can either pass an **array** or an **object** to the
662function. Here is an example using an array::
663
664 $data = array(
665 array(
666 'title' => 'My title',
667 'name' => 'My Name',
668 'date' => 'My date'
669 ),
670 array(
671 'title' => 'Another title',
672 'name' => 'Another Name',
673 'date' => 'Another date'
674 )
675 );
WanWizard7219c072011-12-28 14:09:05 +0100676
Derek Jones8ede1a22011-10-05 13:34:52 -0500677 $this->db->insert_batch('mytable', $data);
678 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
679
680The first parameter will contain the table name, the second is an
681associative array of values.
682
683.. note:: All values are escaped automatically producing safer queries.
684
James L Parry42a7df62014-11-25 12:06:49 -0800685*************
686Updating Data
687*************
688
James L Parry141288d2014-12-06 01:45:12 -0800689**$this->db->replace()**
Andrey Andreev04c50f52012-10-24 23:05:25 +0300690
691This method executes a REPLACE statement, which is basically the SQL
692standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE*
693keys as the determining factor.
694In our case, it will save you from the need to implement complex
695logics with different combinations of ``select()``, ``update()``,
696``delete()`` and ``insert()`` calls.
697
698Example::
699
700 $data = array(
701 'title' => 'My title',
702 'name' => 'My Name',
703 'date' => 'My date'
704 );
705
706 $this->db->replace('table', $data);
707
708 // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
709
710In the above example, if we assume that the *title* field is our primary
711key, then if a row containing 'My title' as the *title* value, that row
712will be deleted with our new row data replacing it.
713
714Usage of the ``set()`` method is also allowed and all fields are
715automatically escaped, just like with ``insert()``.
716
James L Parry141288d2014-12-06 01:45:12 -0800717**$this->db->set()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500718
719This function enables you to set values for inserts or updates.
720
721**It can be used instead of passing a data array directly to the insert
722or update functions:**
723
724::
725
726 $this->db->set('name', $name);
727 $this->db->insert('mytable'); // Produces: INSERT INTO mytable (name) VALUES ('{$name}')
728
729If you use multiple function called they will be assembled properly
730based on whether you are doing an insert or an update::
731
732 $this->db->set('name', $name);
733 $this->db->set('title', $title);
734 $this->db->set('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100735 $this->db->insert('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500736
737**set()** will also accept an optional third parameter ($escape), that
738will prevent data from being escaped if set to FALSE. To illustrate the
739difference, here is set() used both with and without the escape
740parameter.
741
742::
743
744 $this->db->set('field', 'field+1', FALSE);
745 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES (field+1)
746 $this->db->set('field', 'field+1');
747 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES ('field+1')
748
749
750You can also pass an associative array to this function::
751
752 $array = array(
753 'name' => $name,
754 'title' => $title,
755 'status' => $status
756 );
WanWizard7219c072011-12-28 14:09:05 +0100757
Derek Jones8ede1a22011-10-05 13:34:52 -0500758 $this->db->set($array);
759 $this->db->insert('mytable');
760
761Or an object::
762
763 /*
764 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200765 public $title = 'My Title';
766 public $content = 'My Content';
767 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500768 }
769 */
WanWizard7219c072011-12-28 14:09:05 +0100770
Derek Jones8ede1a22011-10-05 13:34:52 -0500771 $object = new Myclass;
772 $this->db->set($object);
773 $this->db->insert('mytable');
774
James L Parry141288d2014-12-06 01:45:12 -0800775**$this->db->update()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500776
777Generates an update string and runs the query based on the data you
778supply. You can pass an **array** or an **object** to the function. Here
779is an example using an array::
780
781 $data = array(
782 'title' => $title,
783 'name' => $name,
784 'date' => $date
785 );
WanWizard7219c072011-12-28 14:09:05 +0100786
Derek Jones8ede1a22011-10-05 13:34:52 -0500787 $this->db->where('id', $id);
788 $this->db->update('mytable', $data);
789 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
790
791Or you can supply an object::
792
793 /*
794 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200795 public $title = 'My Title';
796 public $content = 'My Content';
797 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500798 }
799 */
WanWizard7219c072011-12-28 14:09:05 +0100800
Derek Jones8ede1a22011-10-05 13:34:52 -0500801 $object = new Myclass;
802 $this->db->where('id', $id);
803 $this->db->update('mytable', $object);
804 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
805
806.. note:: All values are escaped automatically producing safer queries.
807
808You'll notice the use of the $this->db->where() function, enabling you
809to set the WHERE clause. You can optionally pass this information
810directly into the update function as a string::
811
812 $this->db->update('mytable', $data, "id = 4");
813
814Or as an array::
815
816 $this->db->update('mytable', $data, array('id' => $id));
817
818You may also use the $this->db->set() function described above when
819performing updates.
820
James L Parry141288d2014-12-06 01:45:12 -0800821**$this->db->update_batch()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500822
823Generates an update string based on the data you supply, and runs the query.
824You can either pass an **array** or an **object** to the function.
825Here is an example using an array::
826
827 $data = array(
828 array(
829 'title' => 'My title' ,
830 'name' => 'My Name 2' ,
831 'date' => 'My date 2'
832 ),
833 array(
834 'title' => 'Another title' ,
835 'name' => 'Another Name 2' ,
836 'date' => 'Another date 2'
837 )
838 );
839
WanWizard7219c072011-12-28 14:09:05 +0100840 $this->db->update_batch('mytable', $data, 'title');
Derek Jones8ede1a22011-10-05 13:34:52 -0500841
WanWizard7219c072011-12-28 14:09:05 +0100842 // Produces:
Derek Jones8ede1a22011-10-05 13:34:52 -0500843 // UPDATE `mytable` SET `name` = CASE
844 // WHEN `title` = 'My title' THEN 'My Name 2'
845 // WHEN `title` = 'Another title' THEN 'Another Name 2'
846 // ELSE `name` END,
WanWizard7219c072011-12-28 14:09:05 +0100847 // `date` = CASE
Derek Jones8ede1a22011-10-05 13:34:52 -0500848 // WHEN `title` = 'My title' THEN 'My date 2'
849 // WHEN `title` = 'Another title' THEN 'Another date 2'
850 // ELSE `date` END
851 // WHERE `title` IN ('My title','Another title')
852
853The first parameter will contain the table name, the second is an associative
854array of values, the third parameter is the where key.
855
856.. note:: All values are escaped automatically producing safer queries.
857
Andrey Andreev9f808b02012-10-24 17:38:48 +0300858.. note:: ``affected_rows()`` won't give you proper results with this method,
859 due to the very nature of how it works. Instead, ``update_batch()``
860 returns the number of rows affected.
861
James L Parry141288d2014-12-06 01:45:12 -0800862**$this->db->get_compiled_update()**
Kyle Farris48d8fb62011-10-14 17:59:49 -0300863
864This works exactly the same way as ``$this->db->get_compiled_insert()`` except
865that it produces an UPDATE SQL string instead of an INSERT SQL string.
866
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200867For more information view documentation for `$this->db->get_compiled_insert()`.
Kyle Farris48d8fb62011-10-14 17:59:49 -0300868
Andrey Andreev6bdfa422013-12-19 15:36:01 +0200869.. note:: This method doesn't work for batched updates.
Derek Jones8ede1a22011-10-05 13:34:52 -0500870
871*************
872Deleting Data
873*************
874
James L Parry141288d2014-12-06 01:45:12 -0800875**$this->db->delete()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500876
877Generates a delete SQL string and runs the query.
878
879::
880
881 $this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
882
883The first parameter is the table name, the second is the where clause.
884You can also use the where() or or_where() functions instead of passing
885the data to the second parameter of the function::
886
887 $this->db->where('id', $id);
888 $this->db->delete('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100889
Derek Jones8ede1a22011-10-05 13:34:52 -0500890 // Produces:
891 // DELETE FROM mytable
892 // WHERE id = $id
893
894
895An array of table names can be passed into delete() if you would like to
896delete data from more than 1 table.
897
898::
899
900 $tables = array('table1', 'table2', 'table3');
901 $this->db->where('id', '5');
902 $this->db->delete($tables);
903
904
905If you want to delete all data from a table, you can use the truncate()
906function, or empty_table().
907
James L Parry141288d2014-12-06 01:45:12 -0800908**$this->db->empty_table()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500909
910Generates a delete SQL string and runs the
911query.::
912
kenjisc35d2c92011-10-26 17:09:17 +0900913 $this->db->empty_table('mytable'); // Produces: DELETE FROM mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500914
James L Parry141288d2014-12-06 01:45:12 -0800915**$this->db->truncate()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500916
917Generates a truncate SQL string and runs the query.
918
919::
920
921 $this->db->from('mytable');
kenjisc35d2c92011-10-26 17:09:17 +0900922 $this->db->truncate();
WanWizard7219c072011-12-28 14:09:05 +0100923
924 // or
925
Derek Jones8ede1a22011-10-05 13:34:52 -0500926 $this->db->truncate('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100927
Derek Jones8ede1a22011-10-05 13:34:52 -0500928 // Produce:
WanWizard7219c072011-12-28 14:09:05 +0100929 // TRUNCATE mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500930
931.. note:: If the TRUNCATE command isn't available, truncate() will
932 execute as "DELETE FROM table".
WanWizard7219c072011-12-28 14:09:05 +0100933
James L Parry141288d2014-12-06 01:45:12 -0800934**$this->db->get_compiled_delete()**
James L Parry42a7df62014-11-25 12:06:49 -0800935
Kyle Farris48d8fb62011-10-14 17:59:49 -0300936This works exactly the same way as ``$this->db->get_compiled_insert()`` except
937that it produces a DELETE SQL string instead of an INSERT SQL string.
938
James L Parry141288d2014-12-06 01:45:12 -0800939For more information view documentation for $this->db->get_compiled_insert().
James L Parry42a7df62014-11-25 12:06:49 -0800940
Derek Jones8ede1a22011-10-05 13:34:52 -0500941***************
942Method Chaining
943***************
944
945Method chaining allows you to simplify your syntax by connecting
946multiple functions. Consider this example::
947
948 $query = $this->db->select('title')
Timothy Warrene464b392012-03-13 14:09:31 -0400949 ->where('id', $id)
950 ->limit(10, 20)
951 ->get('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500952
Derek Jones8ede1a22011-10-05 13:34:52 -0500953.. _ar-caching:
954
955*********************
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000956Query Builder Caching
Derek Jones8ede1a22011-10-05 13:34:52 -0500957*********************
958
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000959While not "true" caching, Query Builder enables you to save (or "cache")
Derek Jones8ede1a22011-10-05 13:34:52 -0500960certain parts of your queries for reuse at a later point in your
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000961script's execution. Normally, when an Query Builder call is completed,
Derek Jones8ede1a22011-10-05 13:34:52 -0500962all stored information is reset for the next call. With caching, you can
963prevent this reset, and reuse information easily.
964
965Cached calls are cumulative. If you make 2 cached select() calls, and
966then 2 uncached select() calls, this will result in 4 select() calls.
967There are three Caching functions available:
968
James L Parry42a7df62014-11-25 12:06:49 -0800969**$this->db->start_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500970
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000971This function must be called to begin caching. All Query Builder queries
Derek Jones8ede1a22011-10-05 13:34:52 -0500972of the correct type (see below for supported queries) are stored for
973later use.
974
James L Parry42a7df62014-11-25 12:06:49 -0800975**$this->db->stop_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500976
977This function can be called to stop caching.
978
James L Parry42a7df62014-11-25 12:06:49 -0800979**$this->db->flush_cache()**
Derek Jones8ede1a22011-10-05 13:34:52 -0500980
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000981This function deletes all items from the Query Builder cache.
Derek Jones8ede1a22011-10-05 13:34:52 -0500982
James L Parry42a7df62014-11-25 12:06:49 -0800983An example of caching
984---------------------
985
Derek Jones8ede1a22011-10-05 13:34:52 -0500986Here's a usage example::
987
988 $this->db->start_cache();
989 $this->db->select('field1');
990 $this->db->stop_cache();
991 $this->db->get('tablename');
992 //Generates: SELECT `field1` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +0100993
Derek Jones8ede1a22011-10-05 13:34:52 -0500994 $this->db->select('field2');
995 $this->db->get('tablename');
996 //Generates: SELECT `field1`, `field2` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +0100997
Derek Jones8ede1a22011-10-05 13:34:52 -0500998 $this->db->flush_cache();
999 $this->db->select('field2');
1000 $this->db->get('tablename');
1001 //Generates: SELECT `field2` FROM (`tablename`)
1002
1003
1004.. note:: The following statements can be cached: select, from, join,
1005 where, like, group_by, having, order_by, set
1006
1007
James L Parry42a7df62014-11-25 12:06:49 -08001008***********************
1009Resetting Query Builder
1010***********************
1011
James L Parry141288d2014-12-06 01:45:12 -08001012**$this->db->reset_query()**
Kyle Farris48d8fb62011-10-14 17:59:49 -03001013
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001014Resetting Query Builder allows you to start fresh with your query without
WanWizard7219c072011-12-28 14:09:05 +01001015executing it first using a method like $this->db->get() or $this->db->insert().
1016Just like the methods that execute a query, this will *not* reset items you've
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001017cached using `Query Builder Caching`_.
Kyle Farris48d8fb62011-10-14 17:59:49 -03001018
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001019This is useful in situations where you are using Query Builder to generate SQL
WanWizard7219c072011-12-28 14:09:05 +01001020(ex. ``$this->db->get_compiled_select()``) but then choose to, for instance,
Kyle Farris48d8fb62011-10-14 17:59:49 -03001021run the query::
1022
1023 // Note that the second parameter of the get_compiled_select method is FALSE
1024 $sql = $this->db->select(array('field1','field2'))
1025 ->where('field3',5)
1026 ->get_compiled_select('mytable', FALSE);
1027
1028 // ...
1029 // Do something crazy with the SQL code... like add it to a cron script for
1030 // later execution or something...
1031 // ...
1032
1033 $data = $this->db->get()->result_array();
1034
1035 // Would execute and return an array of results of the following query:
Andrey Andreev896d3e32014-01-07 17:13:25 +02001036 // SELECT field1, field1 from mytable where field3 = 5;
1037
1038.. note:: Double calls to ``get_compiled_select()`` while you're using the
1039 Query Builder Caching functionality and NOT resetting your queries
1040 will results in the cache being merged twice. That in turn will
James L Parry73817112014-12-08 03:09:29 -08001041 i.e. if you're caching a ``select()`` - select the same field twice.
1042
1043***************
1044Class Reference
1045***************
1046
1047.. class:: CI_DB_query_builder
1048
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001049 .. method:: reset_query()
1050
1051 :returns: CI_DB_query_builder instance (method chaining)
1052 :rtype: CI_DB_query_builder
1053
1054 Resets the current Query Builder state. Useful when you want
1055 to build a query that can be cancelled under certain conditions.
1056
1057 .. method:: start_cache()
1058
1059 :returns: CI_DB_query_builder instance (method chaining)
1060 :rtype: CI_DB_query_builder
1061
1062 Starts the Query Builder cache.
1063
1064 .. method:: stop_cache()
1065
1066 :returns: CI_DB_query_builder instance (method chaining)
1067 :rtype: CI_DB_query_builder
1068
1069 Stops the Query Builder cache.
1070
1071 .. method:: flush_cache()
1072
1073 :returns: CI_DB_query_builder instance (method chaining)
1074 :rtype: CI_DB_query_builder
1075
1076 Empties the Query Builder cache.
1077
1078 .. method:: set_dbprefix([$prefix = ''])
1079
1080 :param string $prefix: The new prefix to use
1081 :returns: The DB prefix in use
1082 :rtype: string
1083
1084 Sets the database prefix, without having to reconnect.
1085
1086 .. method:: dbprefix([$table = ''])
1087
1088 :param string $table: The table name to prefix
1089 :returns: The prefixed table name
1090 :rtype: string
1091
1092 Prepends a database prefix, if one exists in configuration.
1093
James L Parry73817112014-12-08 03:09:29 -08001094 .. method:: count_all_results([$table = ''])
1095
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001096 :param string $table: Table name
James L Parry73817112014-12-08 03:09:29 -08001097 :returns: Number of rows in the query result
1098 :rtype: int
1099
David Wosnitzad31a4e62014-12-12 16:35:35 +01001100 Generates a platform-specific query string that counts
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001101 all records returned by an Query Builder query.
James L Parry73817112014-12-08 03:09:29 -08001102
1103 .. method:: get([$table = ''[, $limit = NULL[, $offset = NULL]]])
1104
1105 :param string $table: The table to query
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001106 :param int $limit: The LIMIT clause
1107 :param int $offset: The OFFSET clause
1108 :returns: CI_DB_result instance (method chaining)
1109 :rtype: CI_DB_result
James L Parry73817112014-12-08 03:09:29 -08001110
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001111 Compiles and runs SELECT statement based on the already
1112 called Query Builder methods.
James L Parry73817112014-12-08 03:09:29 -08001113
1114 .. method:: get_where([$table = ''[, $where = NULL[, $limit = NULL[, $offset = NULL]]]])
1115
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001116 :param mixed $table: The table(s) to fetch data from; string or array
1117 :param string $where: The WHERE clause
1118 :param int $limit: The LIMIT clause
1119 :param int $offset: The OFFSET clause
1120 :returns: CI_DB_result instance (method chaining)
1121 :rtype: CI_DB_result
James L Parry73817112014-12-08 03:09:29 -08001122
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001123 Same as ``get()``, but also allows the WHERE to be added directly.
James L Parry73817112014-12-08 03:09:29 -08001124
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001125 .. method:: select([$select = '*'[, $escape = NULL]])
James L Parry73817112014-12-08 03:09:29 -08001126
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001127 :param string $select: The SELECT portion of a query
1128 :param bool $escape: Whether to escape values and identifiers
1129 :returns: CI_DB_query_builder instance (method chaining)
1130 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001131
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001132 Adds a SELECT clause to a query.
James L Parry73817112014-12-08 03:09:29 -08001133
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001134 .. method:: select_avg([$select = ''[, $alias = '']])
James L Parry73817112014-12-08 03:09:29 -08001135
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001136 :param string $select: Field to compute the average of
1137 :param string $alias: Alias for the resulting value name
1138 :returns: CI_DB_query_builder instance (method chaining)
1139 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001140
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001141 Adds a SELECT AVG(field) clause to a query.
James L Parry73817112014-12-08 03:09:29 -08001142
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001143 .. method:: select_max([$select = ''[, $alias = '']])
James L Parry73817112014-12-08 03:09:29 -08001144
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001145 :param string $select: Field to compute the maximum of
1146 :param string $alias: Alias for the resulting value name
1147 :returns: CI_DB_query_builder instance (method chaining)
1148 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001149
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001150 Adds a SELECT MAX(field) clause to a query.
James L Parry73817112014-12-08 03:09:29 -08001151
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001152 .. method:: select_min([$select = ''[, $alias = '']])
James L Parry73817112014-12-08 03:09:29 -08001153
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001154 :param string $select: Field to compute the minimum of
1155 :param string $alias: Alias for the resulting value name
1156 :returns: CI_DB_query_builder instance (method chaining)
1157 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001158
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001159 Adds a SELECT MIN(field) clause to a query.
James L Parry73817112014-12-08 03:09:29 -08001160
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001161 .. method:: select_sum([$select = ''[, $alias = '']])
James L Parry73817112014-12-08 03:09:29 -08001162
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001163 :param string $select: Field to compute the sum of
1164 :param string $alias: Alias for the resulting value name
1165 :returns: CI_DB_query_builder instance (method chaining)
1166 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001167
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001168 Adds a SELECT SUM(field) clause to a query.
James L Parry73817112014-12-08 03:09:29 -08001169
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001170 .. method:: distinct([$val = TRUE])
James L Parry73817112014-12-08 03:09:29 -08001171
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001172 :param bool $val: Desired value of the "distinct" flag
1173 :returns: CI_DB_query_builder instance (method chaining)
1174 :rtype: CI_DB_query_builder
James L Parry73817112014-12-08 03:09:29 -08001175
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001176 Sets a flag which tells the query builder to add
1177 a DISTINCT clause to the SELECT portion of the query.
1178
1179 .. method:: from($from)
1180
1181 :param mixed $from: Table name(s); string or array
1182 :returns: CI_DB_query_builder instance (method chaining)
1183 :rtype: CI_DB_query_builder
1184
1185 Specifies the FROM clause of a query.
James L Parry73817112014-12-08 03:09:29 -08001186
1187 .. method:: join($table, $cond[, $type = ''[, $escape = NULL]])
1188
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001189 :param string $table: Table name to join
1190 :param string $cond: The JOIN ON condition
James L Parry73817112014-12-08 03:09:29 -08001191 :param string $type: The JOIN type
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001192 :param bool $escape: Whether to escape values and identifiers
1193 :returns: CI_DB_query_builder instance (method chaining)
1194 :rtype: CI_DB_query_builder
1195
1196 Adds a JOIN clause to a query.
1197
1198 .. method:: where($key[, $value = NULL[, $escape = NULL]])
1199
1200 :param mixed $key: Name of field to compare, or associative array
1201 :param mixed $value: If a single key, compared to this value
James L Parry73817112014-12-08 03:09:29 -08001202 :param boolean $escape: Whether to escape values and identifiers
1203 :returns: DB_query_builder instance
1204 :rtype: object
1205
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001206 Generates the WHERE portion of the query.
James L Parry73817112014-12-08 03:09:29 -08001207 Separates multiple calls with 'AND'.
1208
James L Parry73817112014-12-08 03:09:29 -08001209 .. method:: or_where($key[, $value = NULL[, $escape = NULL]])
1210
1211 :param mixed $key: Name of field to compare, or associative array
1212 :param mixed $value: If a single key, compared to this value
1213 :param boolean $escape: Whether to escape values and identifiers
1214 :returns: DB_query_builder instance
1215 :rtype: object
1216
1217 Generates the WHERE portion of the query.
1218 Separates multiple calls with 'OR'.
1219
1220 .. method:: or_where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1221
1222 :param string $key: The field to search
1223 :param array $values: The values searched on
1224 :param boolean $escape: Whether to escape values and identifiers
1225 :returns: DB_query_builder instance
1226 :rtype: object
1227
1228 Generates a WHERE field IN('item', 'item') SQL query,
1229 joined with 'OR' if appropriate.
1230
1231 .. method:: or_where_not_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1232
1233 :param string $key: The field to search
1234 :param array $values: The values searched on
1235 :param boolean $escape: Whether to escape values and identifiers
1236 :returns: DB_query_builder instance
1237 :rtype: object
1238
1239 Generates a WHERE field NOT IN('item', 'item') SQL query,
1240 joined with 'OR' if appropriate.
1241
James L Parry73817112014-12-08 03:09:29 -08001242 .. method:: where_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1243
1244 :param string $key: Name of field to examine
1245 :param array $values: Array of target values
1246 :param boolean $escape: Whether to escape values and identifiers
1247 :returns: DB_query_builder instance
1248 :rtype: object
1249
1250 Generates a WHERE field IN('item', 'item') SQL query,
1251 joined with 'AND' if appropriate.
1252
1253 .. method:: where_not_in([$key = NULL[, $values = NULL[, $escape = NULL]]])
1254
1255 :param string $key: Name of field to examine
1256 :param array $values: Array of target values
1257 :param boolean $escape: Whether to escape values and identifiers
1258 :returns: DB_query_builder instance
1259 :rtype: object
1260
1261 Generates a WHERE field NOT IN('item', 'item') SQL query,
Andrey Andreev4fce5c42014-12-11 17:11:48 +02001262 joined with 'AND' if appropriate.
1263
1264 .. method:: group_start()
1265
1266 :returns: CI_DB_query_builder instance (method chaining)
1267 :rtype: CI_DB_query_builder
1268
1269 Starts a group expression, using ANDs for the conditions inside it.
1270
1271 .. method:: or_group_start()
1272
1273 :returns: CI_DB_query_builder instance (method chaining)
1274 :rtype: CI_DB_query_builder
1275
1276 Starts a group expression, using ORs for the conditions inside it.
1277
1278 .. method:: not_group_start()
1279
1280 :returns: CI_DB_query_builder instance (method chaining)
1281 :rtype: CI_DB_query_builder
1282
1283 Starts a group expression, using AND NOTs for the conditions inside it.
1284
1285 .. method:: or_not_group_start()
1286
1287 :returns: CI_DB_query_builder instance (method chaining)
1288 :rtype: CI_DB_query_builder
1289
1290 Starts a group expression, using OR NOTs for the conditions inside it.
1291
1292 .. method:: group_end()
1293
1294 :returns: DB_query_builder instance
1295 :rtype: object
1296
1297 Ends a group expression.
1298
1299 .. method:: like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1300
1301 :param string $field: Field name
1302 :param string $match: Text portion to match
1303 :param string $side: Which side of the expression to put the '%' wildcard on
1304 :param bool $escape: Whether to escape values and identifiers
1305 :returns: CI_DB_query_builder instance (method chaining)
1306 :rtype: CI_DB_query_builder
1307
1308 Adds a LIKE clause to a query, separating multiple calls with AND.
1309
1310 .. method:: or_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1311
1312 :param string $field: Field name
1313 :param string $match: Text portion to match
1314 :param string $side: Which side of the expression to put the '%' wildcard on
1315 :param bool $escape: Whether to escape values and identifiers
1316 :returns: CI_DB_query_builder instance (method chaining)
1317 :rtype: CI_DB_query_builder
1318
1319 Adds a LIKE clause to a query, separating multiple class with OR.
1320
1321 .. method:: not_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1322
1323 :param string $field: Field name
1324 :param string $match: Text portion to match
1325 :param string $side: Which side of the expression to put the '%' wildcard on
1326 :param bool $escape: Whether to escape values and identifiers
1327 :returns: CI_DB_query_builder instance (method chaining)
1328 :rtype: CI_DB_query_builder
1329
1330 Adds a NOT LIKE clause to a query, separating multiple calls with AND.
1331
1332 .. method:: or_not_like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])
1333
1334 :param string $field: Field name
1335 :param string $match: Text portion to match
1336 :param string $side: Which side of the expression to put the '%' wildcard on
1337 :param bool $escape: Whether to escape values and identifiers
1338 :returns: CI_DB_query_builder instance (method chaining)
1339 :rtype: CI_DB_query_builder
1340
1341 Adds a NOT LIKE clause to a query, separating multiple calls with OR.
1342
1343 .. method:: having($key[, $value = NULL[, $escape = NULL]])
1344
1345 :param mixed $key: Identifier (string) or associative array of field/value pairs
1346 :param string $value: Value sought if $key is an identifier
1347 :param string $escape: Whether to escape values and identifiers
1348 :returns: CI_DB_query_builder instance (method chaining)
1349 :rtype: CI_DB_query_builder
1350
1351 Adds a HAVING clause to a query, separating multiple calls with AND.
1352
1353 .. method:: or_having($key[, $value = NULL[, $escape = NULL]])
1354
1355 :param mixed $key: Identifier (string) or associative array of field/value pairs
1356 :param string $value: Value sought if $key is an identifier
1357 :param string $escape: Whether to escape values and identifiers
1358 :returns: CI_DB_query_builder instance (method chaining)
1359 :rtype: CI_DB_query_builder
1360
1361 Adds a HAVING clause to a query, separating multiple calls with OR.
1362
1363 .. method:: group_by($by[, $escape = NULL])
1364
1365 :param mixed $by: Field(s) to group by; string or array
1366 :returns: CI_DB_query_builder instance (method chaining)
1367 :rtype: CI_DB_query_builder
1368
1369 Adds a GROUP BY clause to a query.
1370
1371 .. method:: order_by($orderby[, $direction = ''[, $escape = NULL]])
1372
1373 :param string $orderby: Field to order by
1374 :param string $direction: The order requested - ASC, DESC or random
1375 :param bool $escape: Whether to escape values and identifiers
1376 :returns: CI_DB_query_builder instance (method chaining)
1377 :rtype: CI_DB_query_builder
1378
1379 Adds an ORDER BY clause to a query.
1380
1381 .. method:: limit($value[, $offset = 0])
1382
1383 :param int $value: Number of rows to limit the results to
1384 :param int $offset: Number of rows to skip
1385 :returns: CI_DB_query_builder instance (method chaining)
1386 :rtype: CI_DB_query_builder
1387
1388 Adds LIMIT and OFFSET clauses to a query.
1389
1390 .. method:: offset($offset)
1391
1392 :param int $offset: Number of rows to skip
1393 :returns: CI_DB_query_builder instance (method chaining)
1394 :rtype: CI_DB_query_builder
1395
1396 Adds an OFFSET clause to a query.
1397
1398 .. method:: set($key[, $value = ''[, $escape = NULL]])
1399
1400 :param mixed $key: Field name, or an array of field/value pairs
1401 :param string $value: Field value, if $key is a single field
1402 :param bool $escape: Whether to escape values and identifiers
1403 :returns: CI_DB_query_builder instance (method chaining)
1404 :rtype: CI_DB_query_builder
1405
1406 Adds field/value pairs to be passed later to ``insert()``,
1407 ``update()`` or ``replace()``.
1408
1409 .. method:: insert([$table = ''[, $set = NULL[, $escape = NULL]]])
1410
1411 :param string $table: Table name
1412 :param array $set: An associative array of field/value pairs
1413 :param bool $escape: Whether to escape values and identifiers
1414 :returns: TRUE on success, FALSE on failure
1415 :rtype: bool
1416
1417 Compiles and executes an INSERT statement.
1418
1419 .. method:: insert_batch([$table = ''[, $set = NULL[, $escape = NULL]]])
1420
1421 :param string $table: Table name
1422 :param array $set: Data to insert
1423 :param bool $escape: Whether to escape values and identifiers
1424 :returns: Number of rows inserted or FALSE on failure
1425 :rtype: mixed
1426
1427 Compiles and executes batch INSERT statements.
1428
1429 .. method:: set_insert_batch($key[, $value = ''[, $escape = NULL]])
1430
1431 :param mixed $key: Field name or an array of field/value pairs
1432 :param string $value: Field value, if $key is a single field
1433 :param bool $escape: Whether to escape values and identifiers
1434 :returns: CI_DB_query_builder instance (method chaining)
1435 :rtype: CI_DB_query_builder
1436
1437 Adds field/value pairs to be inserted in a table later via ``insert_batch()``.
1438
1439 .. method:: update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]])
1440
1441 :param string $table: Table name
1442 :param array $set: An associative array of field/value pairs
1443 :param string $where: The WHERE clause
1444 :param int $limit: The LIMIT clause
1445 :returns: TRUE on success, FALSE on failure
1446 :rtype: bool
1447
1448 Compiles and executes an UPDATE statement.
1449
1450 .. method:: update_batch([$table = ''[, $set = NULL[, $value = NULL]]])
1451
1452 :param string $table: Table name
1453 :param array $set: Field name, or an associative array of field/value pairs
1454 :param string $value: Field value, if $set is a single field
1455 :returns: Number of rows updated or FALSE on failure
1456 :rtype: mixed
1457
1458 Compiles and executes batch UPDATE statements.
1459
1460 .. method:: set_update_batch($key[, $value = ''[, $escape = NULL]])
1461
1462 :param mixed $key: Field name or an array of field/value pairs
1463 :param string $value: Field value, if $key is a single field
1464 :param bool $escape: Whether to escape values and identifiers
1465 :returns: CI_DB_query_builder instance (method chaining)
1466 :rtype: CI_DB_query_builder
1467
1468 Adds field/value pairs to be updated in a table later via ``update_batch()``.
1469
1470 .. method:: replace([$table = ''[, $set = NULL]])
1471
1472 :param string $table: Table name
1473 :param array $set: An associative array of field/value pairs
1474 :returns: TRUE on success, FALSE on failure
1475 :rtype: bool
1476
1477 Compiles and executes a REPLACE statement.
1478
1479 .. method:: delete([$table = ''[, $where = ''[, $limit = NULL[, $reset_data = TRUE]]]])
1480
1481 :param mixed $table: The table(s) to delete from; string or array
1482 :param string $where: The WHERE clause
1483 :param int $limit: The LIMIT clause
1484 :param bool $reset_data: TRUE to reset the query "write" clause
1485 :returns: CI_DB_query_builder instance (method chaining) or FALSE on failure
1486 :rtype: mixed
1487
1488 Compiles and executes a DELETE query.
1489
1490 .. method:: truncate([$table = ''])
1491
1492 :param string $table: Table name
1493 :returns: TRUE on success, FALSE on failure
1494 :rtype: bool
1495
1496 Executes a TRUNCATE statement on a table.
1497
1498 .. note:: If the database platform in use doesn't support TRUNCATE,
1499 a DELETE statement will be used instead.
1500
1501 .. method:: empty_table([$table = ''])
1502
1503 :param string $table: Table name
1504 :returns: TRUE on success, FALSE on failure
1505 :rtype: bool
1506
1507 Deletes all records from a table via a DELETE statement.
1508
1509 .. method:: get_compiled_select([$table = ''[, $reset = TRUE]])
1510
1511 :param string $table: Table name
1512 :param bool $reset: Whether to reset the current QB values or not
1513 :returns: The compiled SQL statement as a string
1514 :rtype: string
1515
1516 Compiles a SELECT statement and returns it as a string.
1517
1518 .. method:: get_compiled_insert([$table = ''[, $reset = TRUE]])
1519
1520 :param string $table: Table name
1521 :param bool $reset: Whether to reset the current QB values or not
1522 :returns: The compiled SQL statement as a string
1523 :rtype: string
1524
1525 Compiles an INSERT statement and returns it as a string.
1526
1527 .. method:: get_compiled_update([$table = ''[, $reset = TRUE]])
1528
1529 :param string $table: Table name
1530 :param bool $reset: Whether to reset the current QB values or not
1531 :returns: The compiled SQL statement as a string
1532 :rtype: string
1533
1534 Compiles an UPDATE statement and returns it as a string.
1535
1536 .. method:: get_compiled_delete([$table = ''[, $reset = TRUE]])
1537
1538 :param string $table: Table name
1539 :param bool $reset: Whether to reset the current QB values or not
1540 :returns: The compiled SQL statement as a string
1541 :rtype: string
1542
David Wosnitzad31a4e62014-12-12 16:35:35 +01001543 Compiles a DELETE statement and returns it as a string.