blob: 65609c1cb5f05ecd15419c2888f02ae7250b6c4e [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
22.. contents:: Page Contents
23
24**************
25Selecting Data
26**************
27
28The following functions allow you to build SQL **SELECT** statements.
29
30$this->db->get()
31================
32
33Runs the selection query and returns the result. Can be used by itself
34to retrieve all records from a table::
35
36 $query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable
37
38The second and third parameters enable you to set a limit and offset
39clause::
40
41 $query = $this->db->get('mytable', 10, 20);
42 // Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
43
44You'll notice that the above function is assigned to a variable named
45$query, which can be used to show the results::
46
47 $query = $this->db->get('mytable');
WanWizard7219c072011-12-28 14:09:05 +010048
Derek Jones8ede1a22011-10-05 13:34:52 -050049 foreach ($query->result() as $row)
50 {
51 echo $row->title;
52 }
53
54Please visit the :doc:`result functions <results>` page for a full
55discussion regarding result generation.
56
Kyle Farris48d8fb62011-10-14 17:59:49 -030057$this->db->get_compiled_select()
58================================
59
WanWizard7219c072011-12-28 14:09:05 +010060Compiles the selection query just like `$this->db->get()`_ but does not *run*
Kyle Farris48d8fb62011-10-14 17:59:49 -030061the query. This method simply returns the SQL query as a string.
62
63Example::
64
65 $sql = $this->db->get_compiled_select('mytable');
66 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +010067
Kyle Farris48d8fb62011-10-14 17:59:49 -030068 // Produces string: SELECT * FROM mytable
WanWizard7219c072011-12-28 14:09:05 +010069
Jamie Rumbelow7efad202012-02-19 12:37:00 +000070The second parameter enables you to set whether or not the query builder query
Kyle Farris48d8fb62011-10-14 17:59:49 -030071will be reset (by default it will be&mdash;just like `$this->db->get()`)::
72
73 echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);
WanWizard7219c072011-12-28 14:09:05 +010074 // Produces string: SELECT * FROM mytable LIMIT 20, 10
Kyle Farris48d8fb62011-10-14 17:59:49 -030075 // (in MySQL. Other databases have slightly different syntax)
WanWizard7219c072011-12-28 14:09:05 +010076
Kyle Farris48d8fb62011-10-14 17:59:49 -030077 echo $this->db->select('title, content, date')->get_compiled_select();
78
79 // Produces string: SELECT title, content, date FROM mytable
WanWizard7219c072011-12-28 14:09:05 +010080
81The key thing to notice in the above example is that the second query did not
82utilize `$this->db->from()`_ and did not pass a table name into the first
83parameter. The reason for this outcome is because the query has not been
84executed using `$this->db->get()`_ which resets values or reset directly
Greg Akerffd24a42011-12-25 22:27:59 -060085using `$this->db->reset_query()`_.
Kyle Farris48d8fb62011-10-14 17:59:49 -030086
Derek Jones84bcc6e2011-10-17 21:24:27 -050087
Derek Jones8ede1a22011-10-05 13:34:52 -050088$this->db->get_where()
89======================
90
91Identical to the above function except that it permits you to add a
92"where" clause in the second parameter, instead of using the db->where()
93function::
94
95 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
96
97Please read the about the where function below for more information.
98
Greg Akerffd24a42011-12-25 22:27:59 -060099.. note:: get_where() was formerly known as getwhere(), which has been removed
Derek Jones8ede1a22011-10-05 13:34:52 -0500100
101$this->db->select()
102===================
103
104Permits you to write the SELECT portion of your query::
105
106 $this->db->select('title, content, date');
107 $query = $this->db->get('mytable'); // Produces: SELECT title, content, date FROM mytable
108
109
110.. note:: If you are selecting all (\*) from a table you do not need to
111 use this function. When omitted, CodeIgniter assumes you wish to SELECT *
112
113$this->db->select() accepts an optional second parameter. If you set it
114to FALSE, CodeIgniter will not try to protect your field or table names
115with backticks. This is useful if you need a compound select statement.
116
117::
118
WanWizard7219c072011-12-28 14:09:05 +0100119 $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 -0500120 $query = $this->db->get('mytable');
121
122
123$this->db->select_max()
124=======================
125
126Writes a "SELECT MAX(field)" portion for your query. You can optionally
127include a second parameter to rename the resulting field.
128
129::
130
131 $this->db->select_max('age');
132 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members
WanWizard7219c072011-12-28 14:09:05 +0100133
Derek Jones8ede1a22011-10-05 13:34:52 -0500134 $this->db->select_max('age', 'member_age');
135 $query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members
136
137
138$this->db->select_min()
139=======================
140
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
151$this->db->select_avg()
152=======================
153
154Writes a "SELECT AVG(field)" portion for your query. As with
155select_max(), You can optionally include a second parameter to rename
156the resulting field.
157
158::
159
160 $this->db->select_avg('age');
161 $query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
162
163
164$this->db->select_sum()
165=======================
166
167Writes a "SELECT SUM(field)" portion for your query. As with
168select_max(), You can optionally include a second parameter to rename
169the resulting field.
170
171::
172
173 $this->db->select_sum('age');
174 $query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members
175
176
177$this->db->from()
178=================
179
180Permits you to write the FROM portion of your query::
181
182 $this->db->select('title, content, date');
183 $this->db->from('mytable');
184 $query = $this->db->get(); // Produces: SELECT title, content, date FROM mytable
185
186.. note:: As shown earlier, the FROM portion of your query can be specified
187 in the $this->db->get() function, so use whichever method you prefer.
188
189$this->db->join()
190=================
191
192Permits you to write the JOIN portion of your query::
193
194 $this->db->select('*');
195 $this->db->from('blogs');
196 $this->db->join('comments', 'comments.id = blogs.id');
197 $query = $this->db->get();
WanWizard7219c072011-12-28 14:09:05 +0100198
Derek Jones8ede1a22011-10-05 13:34:52 -0500199 // Produces:
kenjisc35d2c92011-10-26 17:09:17 +0900200 // SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Derek Jones8ede1a22011-10-05 13:34:52 -0500201
202Multiple function calls can be made if you need several joins in one
203query.
204
205If you need a specific type of JOIN you can specify it via the third
206parameter of the function. Options are: left, right, outer, inner, left
207outer, and right outer.
208
209::
210
211 $this->db->join('comments', 'comments.id = blogs.id', 'left');
212 // Produces: LEFT JOIN comments ON comments.id = blogs.id
213
214$this->db->where()
215==================
216
217This function enables you to set **WHERE** clauses using one of four
218methods:
219
220.. note:: All values passed to this function are escaped automatically,
221 producing safer queries.
222
223#. **Simple key/value method:**
224
225 ::
226
WanWizard7219c072011-12-28 14:09:05 +0100227 $this->db->where('name', $name); // Produces: WHERE name = 'Joe'
Derek Jones8ede1a22011-10-05 13:34:52 -0500228
229 Notice that the equal sign is added for you.
230
231 If you use multiple function calls they will be chained together with
232 AND between them:
233
234 ::
235
236 $this->db->where('name', $name);
237 $this->db->where('title', $title);
238 $this->db->where('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100239 // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500240
241#. **Custom key/value method:**
242 You can include an operator in the first parameter in order to
243 control the comparison:
244
245 ::
246
247 $this->db->where('name !=', $name);
WanWizard7219c072011-12-28 14:09:05 +0100248 $this->db->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500249
250#. **Associative array method:**
251
252 ::
253
254 $array = array('name' => $name, 'title' => $title, 'status' => $status);
255 $this->db->where($array);
WanWizard7219c072011-12-28 14:09:05 +0100256 // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Derek Jones8ede1a22011-10-05 13:34:52 -0500257
258 You can include your own operators using this method as well:
259
260 ::
261
262 $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
263 $this->db->where($array);
264
265#. **Custom string:**
266 You can write your own clauses manually::
267
268 $where = "name='Joe' AND status='boss' OR status='active'";
269 $this->db->where($where);
270
271
272$this->db->where() accepts an optional third parameter. If you set it to
273FALSE, CodeIgniter will not try to protect your field or table names
274with backticks.
275
276::
277
278 $this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
279
280
281$this->db->or_where()
282=====================
283
284This function is identical to the one above, except that multiple
285instances are joined by OR::
286
287 $this->db->where('name !=', $name);
288 $this->db->or_where('id >', $id); // Produces: WHERE name != 'Joe' OR id > 50
289
290.. note:: or_where() was formerly known as orwhere(), which has been
291 removed.
292
293$this->db->where_in()
294=====================
295
296Generates a WHERE field IN ('item', 'item') SQL query joined with AND if
297appropriate
298
299::
300
301 $names = array('Frank', 'Todd', 'James');
302 $this->db->where_in('username', $names);
303 // Produces: WHERE username IN ('Frank', 'Todd', 'James')
304
305
306$this->db->or_where_in()
307========================
308
309Generates a WHERE field IN ('item', 'item') SQL query joined with OR if
310appropriate
311
312::
313
314 $names = array('Frank', 'Todd', 'James');
315 $this->db->or_where_in('username', $names);
316 // Produces: OR username IN ('Frank', 'Todd', 'James')
317
318
319$this->db->where_not_in()
320=========================
321
322Generates a WHERE field NOT IN ('item', 'item') SQL query joined with
323AND if appropriate
324
325::
326
327 $names = array('Frank', 'Todd', 'James');
328 $this->db->where_not_in('username', $names);
329 // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')
330
331
332$this->db->or_where_not_in()
333============================
334
335Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR
336if appropriate
337
338::
339
340 $names = array('Frank', 'Todd', 'James');
341 $this->db->or_where_not_in('username', $names);
342 // Produces: OR username NOT IN ('Frank', 'Todd', 'James')
343
344
345$this->db->like()
346=================
347
Andrey Andreev41738232012-11-30 00:13:17 +0200348This method enables you to generate **LIKE** clauses, useful for doing
Derek Jones8ede1a22011-10-05 13:34:52 -0500349searches.
350
Andrey Andreev41738232012-11-30 00:13:17 +0200351.. note:: All values passed to this method are escaped automatically.
Derek Jones8ede1a22011-10-05 13:34:52 -0500352
353#. **Simple key/value method:**
354
355 ::
356
Andrey Andreev41738232012-11-30 00:13:17 +0200357 $this->db->like('title', 'match');
358 // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500359
Andrey Andreev41738232012-11-30 00:13:17 +0200360 If you use multiple method calls they will be chained together with
Derek Jones8ede1a22011-10-05 13:34:52 -0500361 AND between them::
362
363 $this->db->like('title', 'match');
364 $this->db->like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200365 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500366
367 If you want to control where the wildcard (%) is placed, you can use
368 an optional third argument. Your options are 'before', 'after' and
369 'both' (which is the default).
370
371 ::
372
Andrey Andreev41738232012-11-30 00:13:17 +0200373 $this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
374 $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
375 $this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500376
377#. **Associative array method:**
378
379 ::
380
381 $array = array('title' => $match, 'page1' => $match, 'page2' => $match);
382 $this->db->like($array);
Andrey Andreev41738232012-11-30 00:13:17 +0200383 // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500384
385
386$this->db->or_like()
387====================
388
Andrey Andreev41738232012-11-30 00:13:17 +0200389This method is identical to the one above, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500390instances are joined by OR::
391
392 $this->db->like('title', 'match'); $this->db->or_like('body', $match);
Andrey Andreev41738232012-11-30 00:13:17 +0200393 // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500394
Andrey Andreev41738232012-11-30 00:13:17 +0200395.. note:: ``or_like()`` was formerly known as ``orlike()``, which has been removed.
Derek Jones8ede1a22011-10-05 13:34:52 -0500396
397$this->db->not_like()
398=====================
399
Andrey Andreev41738232012-11-30 00:13:17 +0200400This method is identical to ``like()``, except that it generates
401NOT LIKE statements::
Derek Jones8ede1a22011-10-05 13:34:52 -0500402
Andrey Andreev41738232012-11-30 00:13:17 +0200403 $this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500404
405$this->db->or_not_like()
406========================
407
Andrey Andreev41738232012-11-30 00:13:17 +0200408This method is identical to ``not_like()``, except that multiple
Derek Jones8ede1a22011-10-05 13:34:52 -0500409instances are joined by OR::
410
411 $this->db->like('title', 'match');
412 $this->db->or_not_like('body', 'match');
Andrey Andreev41738232012-11-30 00:13:17 +0200413 // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
Derek Jones8ede1a22011-10-05 13:34:52 -0500414
415$this->db->group_by()
416=====================
417
418Permits you to write the GROUP BY portion of your query::
419
420 $this->db->group_by("title"); // Produces: GROUP BY title
421
422You can also pass an array of multiple values as well::
423
424 $this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
425
426.. note:: group_by() was formerly known as groupby(), which has been
427 removed.
428
429$this->db->distinct()
430=====================
431
432Adds the "DISTINCT" keyword to a query
433
434::
435
436 $this->db->distinct();
437 $this->db->get('table'); // Produces: SELECT DISTINCT * FROM table
438
439
440$this->db->having()
441===================
442
443Permits you to write the HAVING portion of your query. There are 2
444possible syntaxes, 1 argument or 2::
445
446 $this->db->having('user_id = 45'); // Produces: HAVING user_id = 45
WanWizard7219c072011-12-28 14:09:05 +0100447 $this->db->having('user_id', 45); // Produces: HAVING user_id = 45
Derek Jones8ede1a22011-10-05 13:34:52 -0500448
449You can also pass an array of multiple values as well::
450
451 $this->db->having(array('title =' => 'My Title', 'id <' => $id));
452 // Produces: HAVING title = 'My Title', id < 45
453
454
455If you are using a database that CodeIgniter escapes queries for, you
456can prevent escaping content by passing an optional third argument, and
457setting it to FALSE.
458
459::
460
461 $this->db->having('user_id', 45); // Produces: HAVING `user_id` = 45 in some databases such as MySQL
462 $this->db->having('user_id', 45, FALSE); // Produces: HAVING user_id = 45
463
464
465$this->db->or_having()
466======================
467
468Identical to having(), only separates multiple clauses with "OR".
469
470$this->db->order_by()
471=====================
472
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200473Lets you set an ORDER BY clause.
474
475The first parameter contains the name of the column you would like to order by.
476
477The second parameter lets you set the direction of the result.
478Options are **ASC**, **DESC** AND **RANDOM**.
Derek Jones8ede1a22011-10-05 13:34:52 -0500479
480::
481
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200482 $this->db->order_by('title', 'DESC');
483 // Produces: ORDER BY `title` DESC
Derek Jones8ede1a22011-10-05 13:34:52 -0500484
485You can also pass your own string in the first parameter::
486
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200487 $this->db->order_by('title DESC, name ASC');
488 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500489
490Or multiple function calls can be made if you need multiple fields.
491
492::
493
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200494 $this->db->order_by('title', 'DESC');
495 $this->db->order_by('name', 'ASC');
496 // Produces: ORDER BY `title` DESC, `name` ASC
Derek Jones8ede1a22011-10-05 13:34:52 -0500497
Andrey Andreev98e46cf2012-11-13 03:01:42 +0200498If you choose the **RANDOM** direction option, then the first parameters will
499be ignored, unless you specify a numeric seed value.
500
501::
502
503 $this->db->order_by('title', 'RANDOM');
504 // Produces: ORDER BY RAND()
505
506 $this->db->order_by(42, 'RANDOM');
507 // Produces: ORDER BY RAND(42)
Derek Jones8ede1a22011-10-05 13:34:52 -0500508
509.. note:: order_by() was formerly known as orderby(), which has been
510 removed.
511
Andrey Andreev0dfb62f2012-10-30 11:37:15 +0200512.. note:: Random ordering is not currently supported in Oracle and
513 will default to ASC instead.
Derek Jones8ede1a22011-10-05 13:34:52 -0500514
515$this->db->limit()
516==================
517
518Lets you limit the number of rows you would like returned by the query::
519
520 $this->db->limit(10); // Produces: LIMIT 10
521
522The second parameter lets you set a result offset.
523
524::
525
526 $this->db->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
527
528$this->db->count_all_results()
529==============================
530
531Permits you to determine the number of rows in a particular Active
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000532Record query. Queries will accept Query Builder restrictors such as
Derek Jones8ede1a22011-10-05 13:34:52 -0500533where(), or_where(), like(), or_like(), etc. Example::
534
535 echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
536 $this->db->like('title', 'match');
537 $this->db->from('my_table');
WanWizard7219c072011-12-28 14:09:05 +0100538 echo $this->db->count_all_results(); // Produces an integer, like 17
Derek Jones8ede1a22011-10-05 13:34:52 -0500539
540$this->db->count_all()
541======================
542
543Permits you to determine the number of rows in a particular table.
544Submit the table name in the first parameter. Example::
545
546 echo $this->db->count_all('my_table'); // Produces an integer, like 25
547
548**************
WanWizard7219c072011-12-28 14:09:05 +0100549Query grouping
550**************
551
552Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow
Timothy Warrene464b392012-03-13 14:09:31 -0400553you to create queries with complex WHERE clauses. Nested groups are supported. Example::
WanWizard7219c072011-12-28 14:09:05 +0100554
555 $this->db->select('*')->from('my_table')
556 ->group_start()
557 ->where('a', 'a')
558 ->or_group_start()
559 ->where('b', 'b')
560 ->where('c', 'c')
561 ->group_end()
562 ->group_end()
563 ->where('d', 'd')
564 ->get();
565
566 // Generates:
567 // SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
568
569.. note:: groups need to be balanced, make sure every group_start() is matched by a group_end().
570
571$this->db->group_start()
572========================
573
574Starts a new group by adding an opening parenthesis to the WHERE clause of the query.
575
576$this->db->or_group_start()
577===========================
578
579Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR'.
580
581$this->db->not_group_start()
582============================
583
584Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'NOT'.
585
586$this->db->or_not_group_start()
587===============================
588
589Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR NOT'.
590
591$this->db->group_end()
592======================
593
594Ends the current group by adding an closing parenthesis to the WHERE clause of the query.
595
596**************
Derek Jones8ede1a22011-10-05 13:34:52 -0500597Inserting Data
598**************
599
600$this->db->insert()
601===================
602
603Generates an insert string based on the data you supply, and runs the
604query. You can either pass an **array** or an **object** to the
605function. Here is an example using an array::
606
607 $data = array(
608 'title' => 'My title',
609 'name' => 'My Name',
610 'date' => 'My date'
611 );
WanWizard7219c072011-12-28 14:09:05 +0100612
Derek Jones8ede1a22011-10-05 13:34:52 -0500613 $this->db->insert('mytable', $data);
614 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
615
616The first parameter will contain the table name, the second is an
617associative array of values.
618
619Here is an example using an object::
620
621 /*
622 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200623 public $title = 'My Title';
624 public $content = 'My Content';
625 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500626 }
627 */
WanWizard7219c072011-12-28 14:09:05 +0100628
Derek Jones8ede1a22011-10-05 13:34:52 -0500629 $object = new Myclass;
630 $this->db->insert('mytable', $object);
631 // Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
632
633The first parameter will contain the table name, the second is an
634object.
635
636.. note:: All values are escaped automatically producing safer queries.
637
Kyle Farris48d8fb62011-10-14 17:59:49 -0300638$this->db->get_compiled_insert()
639================================
WanWizard7219c072011-12-28 14:09:05 +0100640Compiles the insertion query just like `$this->db->insert()`_ but does not
Kyle Farris48d8fb62011-10-14 17:59:49 -0300641*run* the query. This method simply returns the SQL query as a string.
642
643Example::
644
645 $data = array(
646 'title' => 'My title',
647 'name' => 'My Name',
648 'date' => 'My date'
649 );
WanWizard7219c072011-12-28 14:09:05 +0100650
Kyle Farris48d8fb62011-10-14 17:59:49 -0300651 $sql = $this->db->set($data)->get_compiled_insert('mytable');
652 echo $sql;
WanWizard7219c072011-12-28 14:09:05 +0100653
Kyle Farris48d8fb62011-10-14 17:59:49 -0300654 // Produces string: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
655
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000656The second parameter enables you to set whether or not the query builder query
Kyle Farris48d8fb62011-10-14 17:59:49 -0300657will be reset (by default it will be--just like `$this->db->insert()`_)::
WanWizard7219c072011-12-28 14:09:05 +0100658
Kyle Farris48d8fb62011-10-14 17:59:49 -0300659 echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);
WanWizard7219c072011-12-28 14:09:05 +0100660
Kyle Farris48d8fb62011-10-14 17:59:49 -0300661 // Produces string: INSERT INTO mytable (title) VALUES ('My Title')
WanWizard7219c072011-12-28 14:09:05 +0100662
Kyle Farris48d8fb62011-10-14 17:59:49 -0300663 echo $this->db->set('content', 'My Content')->get_compiled_insert();
664
665 // Produces string: INSERT INTO mytable (title, content) VALUES ('My Title', 'My Content')
WanWizard7219c072011-12-28 14:09:05 +0100666
667The key thing to notice in the above example is that the second query did not
668utlize `$this->db->from()`_ nor did it pass a table name into the first
669parameter. The reason this worked is because the query has not been executed
670using `$this->db->insert()`_ which resets values or reset directly using
Kyle Farris48d8fb62011-10-14 17:59:49 -0300671`$this->db->reset_query()`_.
672
Derek Jones8ede1a22011-10-05 13:34:52 -0500673$this->db->insert_batch()
674=========================
675
676Generates an insert string based on the data you supply, and runs the
677query. You can either pass an **array** or an **object** to the
678function. Here is an example using an array::
679
680 $data = array(
681 array(
682 'title' => 'My title',
683 'name' => 'My Name',
684 'date' => 'My date'
685 ),
686 array(
687 'title' => 'Another title',
688 'name' => 'Another Name',
689 'date' => 'Another date'
690 )
691 );
WanWizard7219c072011-12-28 14:09:05 +0100692
Derek Jones8ede1a22011-10-05 13:34:52 -0500693 $this->db->insert_batch('mytable', $data);
694 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
695
696The first parameter will contain the table name, the second is an
697associative array of values.
698
699.. note:: All values are escaped automatically producing safer queries.
700
Andrey Andreev04c50f52012-10-24 23:05:25 +0300701$this->db->replace()
702====================
703
704This method executes a REPLACE statement, which is basically the SQL
705standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE*
706keys as the determining factor.
707In our case, it will save you from the need to implement complex
708logics with different combinations of ``select()``, ``update()``,
709``delete()`` and ``insert()`` calls.
710
711Example::
712
713 $data = array(
714 'title' => 'My title',
715 'name' => 'My Name',
716 'date' => 'My date'
717 );
718
719 $this->db->replace('table', $data);
720
721 // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
722
723In the above example, if we assume that the *title* field is our primary
724key, then if a row containing 'My title' as the *title* value, that row
725will be deleted with our new row data replacing it.
726
727Usage of the ``set()`` method is also allowed and all fields are
728automatically escaped, just like with ``insert()``.
729
Derek Jones8ede1a22011-10-05 13:34:52 -0500730$this->db->set()
731================
732
733This function enables you to set values for inserts or updates.
734
735**It can be used instead of passing a data array directly to the insert
736or update functions:**
737
738::
739
740 $this->db->set('name', $name);
741 $this->db->insert('mytable'); // Produces: INSERT INTO mytable (name) VALUES ('{$name}')
742
743If you use multiple function called they will be assembled properly
744based on whether you are doing an insert or an update::
745
746 $this->db->set('name', $name);
747 $this->db->set('title', $title);
748 $this->db->set('status', $status);
WanWizard7219c072011-12-28 14:09:05 +0100749 $this->db->insert('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500750
751**set()** will also accept an optional third parameter ($escape), that
752will prevent data from being escaped if set to FALSE. To illustrate the
753difference, here is set() used both with and without the escape
754parameter.
755
756::
757
758 $this->db->set('field', 'field+1', FALSE);
759 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES (field+1)
760 $this->db->set('field', 'field+1');
761 $this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES ('field+1')
762
763
764You can also pass an associative array to this function::
765
766 $array = array(
767 'name' => $name,
768 'title' => $title,
769 'status' => $status
770 );
WanWizard7219c072011-12-28 14:09:05 +0100771
Derek Jones8ede1a22011-10-05 13:34:52 -0500772 $this->db->set($array);
773 $this->db->insert('mytable');
774
775Or an object::
776
777 /*
778 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200779 public $title = 'My Title';
780 public $content = 'My Content';
781 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500782 }
783 */
WanWizard7219c072011-12-28 14:09:05 +0100784
Derek Jones8ede1a22011-10-05 13:34:52 -0500785 $object = new Myclass;
786 $this->db->set($object);
787 $this->db->insert('mytable');
788
Derek Jones8ede1a22011-10-05 13:34:52 -0500789*************
790Updating Data
791*************
792
793$this->db->update()
794===================
795
796Generates an update string and runs the query based on the data you
797supply. You can pass an **array** or an **object** to the function. Here
798is an example using an array::
799
800 $data = array(
801 'title' => $title,
802 'name' => $name,
803 'date' => $date
804 );
WanWizard7219c072011-12-28 14:09:05 +0100805
Derek Jones8ede1a22011-10-05 13:34:52 -0500806 $this->db->where('id', $id);
807 $this->db->update('mytable', $data);
808 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
809
810Or you can supply an object::
811
812 /*
813 class Myclass {
vlakoffff3f7de2012-06-16 14:21:32 +0200814 public $title = 'My Title';
815 public $content = 'My Content';
816 public $date = 'My Date';
Derek Jones8ede1a22011-10-05 13:34:52 -0500817 }
818 */
WanWizard7219c072011-12-28 14:09:05 +0100819
Derek Jones8ede1a22011-10-05 13:34:52 -0500820 $object = new Myclass;
821 $this->db->where('id', $id);
822 $this->db->update('mytable', $object);
823 // Produces: // UPDATE mytable // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id
824
825.. note:: All values are escaped automatically producing safer queries.
826
827You'll notice the use of the $this->db->where() function, enabling you
828to set the WHERE clause. You can optionally pass this information
829directly into the update function as a string::
830
831 $this->db->update('mytable', $data, "id = 4");
832
833Or as an array::
834
835 $this->db->update('mytable', $data, array('id' => $id));
836
837You may also use the $this->db->set() function described above when
838performing updates.
839
Andrey Andreev04c50f52012-10-24 23:05:25 +0300840
Derek Jones8ede1a22011-10-05 13:34:52 -0500841$this->db->update_batch()
842=========================
843
844Generates an update string based on the data you supply, and runs the query.
845You can either pass an **array** or an **object** to the function.
846Here is an example using an array::
847
848 $data = array(
849 array(
850 'title' => 'My title' ,
851 'name' => 'My Name 2' ,
852 'date' => 'My date 2'
853 ),
854 array(
855 'title' => 'Another title' ,
856 'name' => 'Another Name 2' ,
857 'date' => 'Another date 2'
858 )
859 );
860
WanWizard7219c072011-12-28 14:09:05 +0100861 $this->db->update_batch('mytable', $data, 'title');
Derek Jones8ede1a22011-10-05 13:34:52 -0500862
WanWizard7219c072011-12-28 14:09:05 +0100863 // Produces:
Derek Jones8ede1a22011-10-05 13:34:52 -0500864 // UPDATE `mytable` SET `name` = CASE
865 // WHEN `title` = 'My title' THEN 'My Name 2'
866 // WHEN `title` = 'Another title' THEN 'Another Name 2'
867 // ELSE `name` END,
WanWizard7219c072011-12-28 14:09:05 +0100868 // `date` = CASE
Derek Jones8ede1a22011-10-05 13:34:52 -0500869 // WHEN `title` = 'My title' THEN 'My date 2'
870 // WHEN `title` = 'Another title' THEN 'Another date 2'
871 // ELSE `date` END
872 // WHERE `title` IN ('My title','Another title')
873
874The first parameter will contain the table name, the second is an associative
875array of values, the third parameter is the where key.
876
877.. note:: All values are escaped automatically producing safer queries.
878
Andrey Andreev9f808b02012-10-24 17:38:48 +0300879.. note:: ``affected_rows()`` won't give you proper results with this method,
880 due to the very nature of how it works. Instead, ``update_batch()``
881 returns the number of rows affected.
882
Kyle Farris48d8fb62011-10-14 17:59:49 -0300883$this->db->get_compiled_update()
884================================
885
886This works exactly the same way as ``$this->db->get_compiled_insert()`` except
887that it produces an UPDATE SQL string instead of an INSERT SQL string.
888
Greg Akerffd24a42011-12-25 22:27:59 -0600889For more information view documentation for `$this->db->get_compiled_insert()`_.
Kyle Farris48d8fb62011-10-14 17:59:49 -0300890
Derek Jones8ede1a22011-10-05 13:34:52 -0500891
892*************
893Deleting Data
894*************
895
896$this->db->delete()
897===================
898
899Generates a delete SQL string and runs the query.
900
901::
902
903 $this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
904
905The first parameter is the table name, the second is the where clause.
906You can also use the where() or or_where() functions instead of passing
907the data to the second parameter of the function::
908
909 $this->db->where('id', $id);
910 $this->db->delete('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100911
Derek Jones8ede1a22011-10-05 13:34:52 -0500912 // Produces:
913 // DELETE FROM mytable
914 // WHERE id = $id
915
916
917An array of table names can be passed into delete() if you would like to
918delete data from more than 1 table.
919
920::
921
922 $tables = array('table1', 'table2', 'table3');
923 $this->db->where('id', '5');
924 $this->db->delete($tables);
925
926
927If you want to delete all data from a table, you can use the truncate()
928function, or empty_table().
929
930$this->db->empty_table()
931========================
932
933Generates a delete SQL string and runs the
934query.::
935
kenjisc35d2c92011-10-26 17:09:17 +0900936 $this->db->empty_table('mytable'); // Produces: DELETE FROM mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500937
938
939$this->db->truncate()
940=====================
941
942Generates a truncate SQL string and runs the query.
943
944::
945
946 $this->db->from('mytable');
kenjisc35d2c92011-10-26 17:09:17 +0900947 $this->db->truncate();
WanWizard7219c072011-12-28 14:09:05 +0100948
949 // or
950
Derek Jones8ede1a22011-10-05 13:34:52 -0500951 $this->db->truncate('mytable');
WanWizard7219c072011-12-28 14:09:05 +0100952
Derek Jones8ede1a22011-10-05 13:34:52 -0500953 // Produce:
WanWizard7219c072011-12-28 14:09:05 +0100954 // TRUNCATE mytable
Derek Jones8ede1a22011-10-05 13:34:52 -0500955
956.. note:: If the TRUNCATE command isn't available, truncate() will
957 execute as "DELETE FROM table".
WanWizard7219c072011-12-28 14:09:05 +0100958
Kyle Farris48d8fb62011-10-14 17:59:49 -0300959$this->db->get_compiled_delete()
960================================
961This works exactly the same way as ``$this->db->get_compiled_insert()`` except
962that it produces a DELETE SQL string instead of an INSERT SQL string.
963
Greg Akerffd24a42011-12-25 22:27:59 -0600964For more information view documentation for `$this->db->get_compiled_insert()`_.
Derek Jones8ede1a22011-10-05 13:34:52 -0500965
966***************
967Method Chaining
968***************
969
970Method chaining allows you to simplify your syntax by connecting
971multiple functions. Consider this example::
972
973 $query = $this->db->select('title')
Timothy Warrene464b392012-03-13 14:09:31 -0400974 ->where('id', $id)
975 ->limit(10, 20)
976 ->get('mytable');
Derek Jones8ede1a22011-10-05 13:34:52 -0500977
Derek Jones8ede1a22011-10-05 13:34:52 -0500978.. _ar-caching:
979
980*********************
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000981Query Builder Caching
Derek Jones8ede1a22011-10-05 13:34:52 -0500982*********************
983
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000984While not "true" caching, Query Builder enables you to save (or "cache")
Derek Jones8ede1a22011-10-05 13:34:52 -0500985certain parts of your queries for reuse at a later point in your
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000986script's execution. Normally, when an Query Builder call is completed,
Derek Jones8ede1a22011-10-05 13:34:52 -0500987all stored information is reset for the next call. With caching, you can
988prevent this reset, and reuse information easily.
989
990Cached calls are cumulative. If you make 2 cached select() calls, and
991then 2 uncached select() calls, this will result in 4 select() calls.
992There are three Caching functions available:
993
994$this->db->start_cache()
995========================
996
Jamie Rumbelow7efad202012-02-19 12:37:00 +0000997This function must be called to begin caching. All Query Builder queries
Derek Jones8ede1a22011-10-05 13:34:52 -0500998of the correct type (see below for supported queries) are stored for
999later use.
1000
1001$this->db->stop_cache()
1002=======================
1003
1004This function can be called to stop caching.
1005
1006$this->db->flush_cache()
1007========================
1008
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001009This function deletes all items from the Query Builder cache.
Derek Jones8ede1a22011-10-05 13:34:52 -05001010
1011Here's a usage example::
1012
1013 $this->db->start_cache();
1014 $this->db->select('field1');
1015 $this->db->stop_cache();
1016 $this->db->get('tablename');
1017 //Generates: SELECT `field1` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +01001018
Derek Jones8ede1a22011-10-05 13:34:52 -05001019 $this->db->select('field2');
1020 $this->db->get('tablename');
1021 //Generates: SELECT `field1`, `field2` FROM (`tablename`)
WanWizard7219c072011-12-28 14:09:05 +01001022
Derek Jones8ede1a22011-10-05 13:34:52 -05001023 $this->db->flush_cache();
1024 $this->db->select('field2');
1025 $this->db->get('tablename');
1026 //Generates: SELECT `field2` FROM (`tablename`)
1027
1028
1029.. note:: The following statements can be cached: select, from, join,
1030 where, like, group_by, having, order_by, set
1031
1032
Greg Akerffd24a42011-12-25 22:27:59 -06001033$this->db->reset_query()
1034========================
Kyle Farris48d8fb62011-10-14 17:59:49 -03001035
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001036Resetting Query Builder allows you to start fresh with your query without
WanWizard7219c072011-12-28 14:09:05 +01001037executing it first using a method like $this->db->get() or $this->db->insert().
1038Just like the methods that execute a query, this will *not* reset items you've
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001039cached using `Query Builder Caching`_.
Kyle Farris48d8fb62011-10-14 17:59:49 -03001040
Jamie Rumbelow7efad202012-02-19 12:37:00 +00001041This is useful in situations where you are using Query Builder to generate SQL
WanWizard7219c072011-12-28 14:09:05 +01001042(ex. ``$this->db->get_compiled_select()``) but then choose to, for instance,
Kyle Farris48d8fb62011-10-14 17:59:49 -03001043run the query::
1044
1045 // Note that the second parameter of the get_compiled_select method is FALSE
1046 $sql = $this->db->select(array('field1','field2'))
1047 ->where('field3',5)
1048 ->get_compiled_select('mytable', FALSE);
1049
1050 // ...
1051 // Do something crazy with the SQL code... like add it to a cron script for
1052 // later execution or something...
1053 // ...
1054
1055 $data = $this->db->get()->result_array();
1056
1057 // Would execute and return an array of results of the following query:
Andrey Andreev41738232012-11-30 00:13:17 +02001058 // SELECT field1, field1 from mytable where field3 = 5;