summaryrefslogtreecommitdiffstats
path: root/user_guide/database/active_record.html
blob: 5a31be2db004d8081bc8171c2bf3b95d6e253336 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Active Record : CodeIgniter User Guide</title>

<style type='text/css' media='all'>@import url('../userguide.css');</style>
<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />

<script type="text/javascript" src="../nav/nav.js"></script>
<script type="text/javascript" src="../nav/prototype.lite.js"></script>
<script type="text/javascript" src="../nav/moo.fx.js"></script>
<script type="text/javascript" src="../nav/user_guide_menu.js"></script>

<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />
<meta name='author' content='ExpressionEngine Dev Team' />
<meta name='description' content='CodeIgniter User Guide' />
</head>
<body>

<!-- START NAVIGATION -->
<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
<div id="masthead">
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td><h1>CodeIgniter User Guide Version 2.1.4</h1></td>
<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
</tr>
</table>
</div>
<!-- END NAVIGATION -->


<!-- START BREADCRUMB -->
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td id="breadcrumb">
<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
<a href="index.html">Database Library</a> &nbsp;&#8250;&nbsp;
Active Record
</td>
<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="ellislab.com/codeigniter/user-guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td>
</tr>
</table>
<!-- END BREADCRUMB -->

<br clear="all" />

<!-- START CONTENT -->
<div id="content">

<h1>Active Record Class</h1>

<p>CodeIgniter uses a modified version of the Active Record Database Pattern.
This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting.
In some cases only one or two lines of code are necessary to perform a database action.
CodeIgniter does not require that each database table be its own class file.  It instead provides a more simplified interface.</p>

<p>Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax
is generated by each database adapter.  It also allows for safer queries, since the values are escaped automatically by the system.</p>

<p class="important"><strong>Note:</strong>  If you intend to write your own queries you can disable this class in your database config file, allowing the core database library and adapter to utilize fewer resources.<br /></p>

<ul>
<li><a href="#select">Selecting Data</a></li>
<li><a href="#insert">Inserting Data</a></li>
<li><a href="#update">Updating Data</a></li>
<li><a href="#delete">Deleting Data</a></li>
<li><a href="#chaining">Method Chaining</a></li>
<li><a href="#caching">Active Record Caching</a></li>
</ul>

<h1><a name="select">&nbsp;</a>Selecting Data</h1>

<p>The following functions allow you to build SQL <strong>SELECT</strong> statements.</p>

<p><strong>Note: If you are using PHP 5 you can use method chaining for more compact syntax. This is described at the end of the page.</strong></p>


<h2>$this->db->get();</h2>

<p>Runs the selection query and returns the result.  Can be used by itself to retrieve all records from a table:</p>

<code>$query = $this->db->get('mytable');<br />
<br />
// Produces: SELECT * FROM mytable</code>

<p>The second and third parameters enable you to set a limit and offset clause:</p>

<code>$query = $this->db->get('mytable', 10, 20);<br />
<br />
// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)</code>

<p>You'll notice that the above function is assigned to a variable named <kbd>$query</kbd>, which can be used to show the results:</p>

<code>$query = $this->db->get('mytable');<br />
<br />
foreach ($query->result() as $row)<br />
{<br />
&nbsp;&nbsp;&nbsp;&nbsp;echo $row->title;<br />
}</code>

<p>Please visit the <a href="results.html">result functions</a> page for a full discussion regarding result generation.</p>


<h2>$this->db->get_where();</h2>

<p>Identical to the above function except that it permits you to add a "where" clause in the second parameter,
instead of using the db->where() function:</p>

<code>$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);</code>

<p>Please read the about the where function below for more information.</p>
<p class="important">Note: get_where() was formerly known as getwhere(), which has been removed</p>

<h2>$this->db->select();</h2>
<p>Permits you to write the SELECT portion of your query:</p>
<p><code>
$this->db->select('title, content, date');<br />
<br />
$query = $this->db->get('mytable');<br />
<br />
// Produces: SELECT title, content, date FROM mytable</code></p>
<p class="important"><strong>Note:</strong> If you are selecting all (*) from a table you do not need to use this function.  When omitted, CodeIgniter assumes you wish to SELECT *</p>

<p>$this-&gt;db-&gt;select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.</p>
<p><code>$this-&gt;db-&gt;select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); <br />
$query = $this-&gt;db-&gt;get('mytable');<br />
</code></p>
<h2>$this->db->select_max();</h2>
<p>Writes a "SELECT MAX(field)" portion for your query. You can optionally include a second parameter to rename the resulting field.</p>
<p><code>
$this->db->select_max('age');<br />
$query = $this->db->get('members');<br />

// Produces: SELECT MAX(age) as age FROM members<br />
<br />
$this-&gt;db-&gt;select_max('age', 'member_age');<br />
$query = $this-&gt;db-&gt;get('members');<br />
// Produces: SELECT MAX(age) as member_age FROM members</code></p>

<h2>$this->db->select_min();</h2>
<p>Writes a "SELECT MIN(field)" portion for your query. As with <dfn>select_max()</dfn>, You can optionally include a second parameter to rename the resulting field.</p>
<p><code>
$this->db->select_min('age');<br />
$query = $this->db->get('members');<br />
// Produces: SELECT MIN(age) as age FROM members</code></p>

<h2>$this->db->select_avg();</h2>
<p>Writes a "SELECT AVG(field)" portion for your query. As with <dfn>select_max()</dfn>, You can optionally include a second parameter to rename the resulting field.</p>
<p><code>
$this->db->select_avg('age');<br />
$query = $this->db->get('members');<br />
// Produces: SELECT AVG(age) as age FROM members</code></p>

<h2>$this->db->select_sum();</h2>
<p>Writes a "SELECT SUM(field)" portion for your query. As with <dfn>select_max()</dfn>, You can optionally include a second parameter to rename the resulting field.</p>
<p><code>
$this->db->select_sum('age');<br />
$query = $this->db->get('members');<br />
// Produces: SELECT SUM(age) as age FROM members</code></p>

<h2>$this->db->from();</h2>

<p>Permits you to write the FROM portion of your query:</p>

<code>
$this->db->select('title, content, date');<br />
$this->db->from('mytable');<br />
<br />
$query = $this->db->get();<br />
<br />
// Produces: SELECT title, content, date FROM mytable</code>

<p class="important">Note: As shown earlier, the FROM portion of your query can be specified in the <dfn>$this->db->get()</dfn> function, so use whichever method
you prefer.</p>

<h2>$this->db->join();</h2>

<p>Permits you to write the JOIN portion of your query:</p>

<code>
$this->db->select('*');<br />
$this->db->from('blogs');<br />
$this->db->join('comments', 'comments.id = blogs.id');<br />
<br />
$query = $this->db->get();<br />
<br />
// Produces: <br />
// SELECT * FROM blogs<br />
// JOIN comments ON comments.id = blogs.id<br />
</code>

<p>Multiple function calls can be made if you need several joins in one query.</p>

<p>If you need a specific type of JOIN you can specify it via the third parameter of the function.
Options are: left, right, outer, inner, left outer, and right outer.</p>

<code>
$this->db->join('comments', 'comments.id = blogs.id', <strong>'left'</strong>);<br />
<br />
// Produces: LEFT JOIN comments ON comments.id = blogs.id</code>





<h2>$this->db->where();</h2>
<p>This function enables you to set <strong>WHERE</strong> clauses using one of four methods:</p>

<p class="important"><strong>Note:</strong> All values passed to this function are escaped automatically, producing safer queries.</p>

<ol>
	<li><strong>Simple key/value method:</strong>

	<code>$this->db->where('name', $name);
	<br /><br />// Produces: WHERE name = 'Joe'	</code>

	<p>Notice that the equal sign is added for you.</p>

	<p>If you use multiple function calls they will be chained together with <var>AND</var> between them:</p>

	<code>$this->db->where('name', $name);<br />
	$this->db->where('title', $title);<br />
	$this->db->where('status', $status);
	<br /><br />// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'	</code>	</li>

	<li><strong>Custom key/value method:</strong>

	<p>You can include an operator in the first parameter in order to control the comparison:</p>

	<code>$this->db->where('name !=', $name);<br />
	$this->db->where('id <', $id);
	<br /><br />// Produces: WHERE name != 'Joe' AND id < 45	</code>	</li>
	<li><strong>Associative array method:</strong>


	<code>
	$array = array('name' => $name, 'title' => $title, 'status' => $status);<br /><br />

	$this->db->where($array);
	<br /><br />// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'	</code>

	<p>You can include your own operators using this method as well:</p>

	<code>
	$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);<br /><br />

	$this->db->where($array);</code>	</li>
		<li><strong>Custom string:</strong>

		<p>You can write your own clauses manually:</p>

		<code>
		$where = "name='Joe' AND status='boss' OR status='active'";<br /><br />
		$this->db->where($where);</code></li>
	</ol>


<p>$this-&gt;db-&gt;where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.</p>
<p><code>		$this-&gt;db-&gt;where('MATCH (field) AGAINST (&quot;value&quot;)', NULL, FALSE);<br />
</code></p>
<h2>$this->db->or_where();</h2>
<p>This function is identical to the one above, except that multiple instances are joined by OR:</p>

<code>
$this->db->where('name !=', $name);<br />
$this->db->or_where('id >', $id);
<br />
<br />// Produces: WHERE name != 'Joe' OR id > 50</code>

<p class="important">Note: or_where() was formerly known as orwhere(), which has been removed.</p>


<h2>$this->db->where_in();</h2>
<p>Generates a WHERE field IN ('item', 'item') SQL query joined with  AND if appropriate</p>
<p><code>
	$names = array('Frank', 'Todd', 'James');<br />
	$this->db->where_in('username', $names);<br />
	// Produces: WHERE username IN ('Frank', 'Todd', 'James')</code></p>

<h2>$this->db->or_where_in();</h2>
<p>Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate</p>
<p><code>
	$names = array('Frank', 'Todd', 'James');<br />
	$this->db->or_where_in('username', $names);<br />
	// Produces: OR username IN ('Frank', 'Todd', 'James')</code></p>

<h2>$this->db->where_not_in();</h2>
<p>Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate</p>
<p><code>
	$names = array('Frank', 'Todd', 'James');<br />
	$this->db->where_not_in('username', $names);<br />
	// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')</code></p>

<h2>$this->db->or_where_not_in();</h2>
<p>Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate</p>
<p><code>
	$names = array('Frank', 'Todd', 'James');<br />
	$this->db->or_where_not_in('username', $names);<br />
	// Produces: OR username NOT IN ('Frank', 'Todd', 'James')</code></p>

<h2>$this->db->like();</h2>
<p>This function enables you to generate <strong>LIKE</strong> clauses, useful for doing searches.</p>

<p class="important"><strong>Note:</strong> All values passed to this function are escaped automatically.</p>


<ol>
	<li><strong>Simple key/value method:</strong>

	<code>$this->db->like('title', 'match');
	<br /><br />// Produces: WHERE title LIKE '%match%'	</code>

	<p>If you use multiple function calls they will be chained together with <var>AND</var> between them:</p>

	<code>$this->db->like('title', 'match');<br />
	$this->db->like('body', 'match');
	<br /><br />
	// WHERE title LIKE '%match%' AND  body LIKE '%match%</code>
	If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default).
	<code>$this->db->like('title', 'match', 'before');
	<br />
		// Produces: WHERE title LIKE '%match'	<br />
		<br />
	$this-&gt;db-&gt;like('title', 'match', 'after'); <br />
// Produces: WHERE title LIKE 'match%' <br />
<br />
	$this-&gt;db-&gt;like('title', 'match', 'both'); <br />
// Produces: WHERE title LIKE '%match%' </code>	</li>

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

<code>
	$this-&gt;db-&gt;like('title', 'match', 'none'); <br />
// Produces: WHERE title LIKE 'match'
</code>

	<li><strong>Associative array method:</strong>

	<code>
	$array = array('title' => $match, 'page1' => $match, 'page2' => $match);<br /><br />

	$this->db->like($array);
	<br /><br />// WHERE title LIKE '%match%' AND  page1 LIKE '%match%' AND  page2 LIKE '%match%'</code></li>
	</ol>


<h2>$this->db->or_like();</h2>
<p>This function is identical to the one above, except that multiple instances are joined by OR:</p>

<code>
$this->db->like('title', 'match');<br />
$this->db->or_like('body', $match);
<br />
<br />// WHERE title LIKE '%match%' OR  body LIKE '%match%'</code>




<p class="important">Note: or_like() was formerly known as orlike(), which has been removed.</p>
<h2>$this-&gt;db-&gt;not_like();</h2>
<p>This function is identical to <strong>like()</strong>, except that it generates NOT LIKE statements:</p>
<code> $this-&gt;db-&gt;not_like('title', 'match');<br />
<br />
// WHERE title NOT LIKE '%match%</code>
<h2>$this-&gt;db-&gt;or_not_like();</h2>
<p>This function is identical to <strong>not_like()</strong>, except that multiple instances are joined by OR:</p>
<code> $this-&gt;db-&gt;like('title', 'match');<br />
$this-&gt;db-&gt;or_not_like('body', 'match'); <br />
<br />
// WHERE title  LIKE '%match% OR body NOT LIKE '%match%'</code>
<h2>$this->db->group_by();</h2>
<p>Permits you to write the GROUP BY portion of your query:</p>

<code>$this->db->group_by("title");
<br /><br />// Produces: GROUP BY title
</code>

<p>You can also pass an array of multiple values as well:</p>

<code>$this->db->group_by(array("title", "date"));
<br />
<br />// Produces: GROUP BY title, date</code>

<p class="important">Note: group_by() was formerly known as groupby(), which has been removed. </p>

<h2> $this-&gt;db-&gt;distinct();<br />
</h2>
<p>Adds the &quot;DISTINCT&quot; keyword to  a query</p>
<p><code>$this-&gt;db-&gt;distinct();<br />
	$this-&gt;db-&gt;get('table');<br />
		<br />
	// Produces: SELECT DISTINCT * FROM table</code></p>
<h2>$this->db->having();</h2>
<p>Permits you to write the HAVING portion of your query. There are 2 possible syntaxes, 1 argument or 2:</p>

<code>$this->db->having('user_id = 45');
<br />
// Produces: HAVING user_id = 45<br />
<br />
$this-&gt;db-&gt;having('user_id',  45); <br />
// Produces: HAVING user_id = 45<br />
<br />
</code>

<p>You can also pass an array of multiple values as well:</p>


<p><code>$this->db->having(array('title =' => 'My Title', 'id <' => $id)); <br />
		<br />
	// Produces: HAVING title = 'My Title', id < 45</code></p>
<p>If you are using a database that CodeIgniter escapes queries for, you can prevent escaping content by passing an optional third argument, and setting it to FALSE.</p>
<p><code>$this-&gt;db-&gt;having('user_id',  45); <br />
// Produces: HAVING `user_id` = 45 in some databases such as MySQL
		<br />
		$this-&gt;db-&gt;having('user_id',  45, FALSE); <br />
// Produces: HAVING user_id = 45</code></p>
<h2>$this-&gt;db-&gt;or_having();</h2>
<p>Identical to having(), only separates multiple clauses with &quot;OR&quot;.</p>
<h2>$this->db->order_by();</h2>
<p>Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by.
The second parameter lets you set the direction of the result.  Options are <kbd>asc</kbd> or <kbd>desc</kbd>, or <kbd>random</kbd>. </p>

<code>$this->db->order_by("title", "desc");
<br />
<br />// Produces: ORDER BY title DESC
</code>

<p>You can also pass your own string in the first parameter:</p>

<code>$this->db->order_by('title desc, name asc');
<br />
<br />// Produces: ORDER BY title DESC, name ASC
</code>

<p>Or multiple function calls can be made if you need multiple fields.</p>

<p><code>$this->db->order_by("title", "desc");<br />
	$this->db->order_by("name", "asc"); <br />
	<br />
	// Produces: ORDER BY title DESC, name ASC
	</code></p>
<p class="important">Note: order_by() was formerly known as orderby(), which has been removed.</p>
<p class="important">Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to 'ASC'.</p>
<h2>$this->db->limit();</h2>
<p>Lets you limit the number of rows you would like returned by the query:</p>

<code>
$this->db->limit(10);<br />
<br />
// Produces: LIMIT 10</code>


<p>The second parameter lets you set a result offset.</p>

<code>
$this->db->limit(10, 20);<br />
<br />
// Produces: LIMIT 20, 10 (in MySQL.  Other databases have slightly different syntax)</code>


<h2>$this->db->count_all_results();</h2>

<p>Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(),  or_where(), like(), or_like(), etc. Example:</p>
<code>echo $this->db->count_all_results('<var>my_table</var>');<br />

// Produces an integer, like 25<br />
<br />
$this-&gt;db-&gt;like('title', 'match');<br />
$this-&gt;db-&gt;from('<var>my_table</var>');<br />
echo $this-&gt;db-&gt;count_all_results();<br />
// Produces an integer, like 17 </code>

<h2>$this->db->count_all();</h2>

<p>Permits you to determine the number of rows in a particular table.  Submit the table name in the first parameter. Example:</p>

<code>echo $this->db->count_all('<var>my_table</var>');<br />
<br />
// Produces an integer, like 25</code>



<a name="insert">&nbsp;</a>
<h1>Inserting Data</h1>

<h2>$this->db->insert();</h2>
<p>Generates an insert string based on the data you supply, and runs the query. You can either pass an
<strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>

<code>
$data = array(<br />
&nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
&nbsp;&nbsp;&nbsp;'name' => 'My Name' ,<br />
&nbsp;&nbsp;&nbsp;'date' => 'My date'<br />
);<br />
<br />
$this->db->insert('mytable', $data);
<br /><br />
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')</code>

<p>The first parameter will contain the table name, the second is an associative array of values.</p>

<p>Here is an example using an object:</p>

<code>
/*<br />
&nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
*/<br />
<br />
$object = new Myclass;<br />
<br />
$this->db->insert('mytable', $object);
<br /><br />
// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')</code>

<p>The first parameter will contain the table name, the second is an object.</p>

<p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>

<h2>$this->db->insert_batch();</h2>
<p>Generates an insert string based on the data you supply, and runs the query. You can either pass an
<strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>

<code>
$data = array(<br/>
&nbsp;&nbsp;&nbsp;array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'My Name' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'My date'<br />
&nbsp;&nbsp;&nbsp;),<br />
&nbsp;&nbsp;&nbsp;array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'Another title' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'Another Name' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'Another date'<br />
&nbsp;&nbsp;&nbsp;)<br/>
);<br />
<br />
$this->db->insert_batch('mytable', $data);
<br /><br />
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')</code>

<p>The first parameter will contain the table name, the second is an associative array of values.</p>

<p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>



<h2>$this->db->set();</h2>
<p>This function enables you to set values for <dfn>inserts</dfn> or <dfn>updates</dfn>.</p>

<p><strong>It can be used instead of passing a data array directly to the insert or update functions:</strong> </p>

<code>$this->db->set('name', $name);
<br />
$this->db->insert('mytable');
<br /><br />
// Produces: INSERT INTO mytable (name) VALUES ('{$name}')</code>

<p>If you use multiple function called they will be assembled properly based on whether you are doing an insert or an update:</p>

<code>$this-&gt;db-&gt;set('name', $name);<br />
$this-&gt;db-&gt;set('title', $title);<br />
$this-&gt;db-&gt;set('status', $status);<br />
$this-&gt;db-&gt;insert('mytable'); </code>
<p><strong>set()</strong> will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE. To illustrate the difference, here is set() used both with and without the escape parameter.</p>
<p><code>$this-&gt;db-&gt;set('field', 'field+1', FALSE);<br />
	$this-&gt;db-&gt;insert('mytable'); <br />
	// gives INSERT INTO mytable (field) VALUES (field+1)<br />
	<br />
	$this-&gt;db-&gt;set('field', 'field+1');<br />
	$this-&gt;db-&gt;insert('mytable'); <br />
	// gives INSERT INTO mytable (field) VALUES ('field+1')</code></p>
<p>You can also pass an associative array to this function:</p>
<code>
$array = array('name' => $name, 'title' => $title, 'status' => $status);<br /><br />

$this->db->set($array);<br />
$this->db->insert('mytable');
</code>

<p>Or an object:</p>


<code>
/*<br />
&nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
*/<br />
<br />
$object = new Myclass;<br />
<br />
$this->db->set($object);<br />
$this->db->insert('mytable');
</code>



<a name="update">&nbsp;</a>
<h1>Updating Data</h1>

<h2>$this->db->update();</h2>
<p>Generates an update string and runs the query based on the data you supply.  You can pass an
<strong>array</strong> or an <strong>object</strong> to the function. Here is an example using
an array:</p>

<code>
$data = array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => $title,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => $name,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => $date<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br />
<br />
$this->db->where('id', $id);<br />
$this->db->update('mytable', $data);
<br /><br />
// Produces:<br />
// UPDATE mytable <br />
// SET title = '{$title}', name = '{$name}', date = '{$date}'<br />
// WHERE id = $id</code>

<p>Or you can supply an object:</p>

<code>
/*<br />
&nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
*/<br />
<br />
$object = new Myclass;<br />
<br />
$this->db->where('id', $id);<br />
$this->db->update('mytable', $object);
<br />
<br />
// Produces:<br />
// UPDATE mytable <br />
// SET title = '{$title}', name = '{$name}', date = '{$date}'<br />
// WHERE id = $id</code>



<p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>

<p>You'll notice the use of the <dfn>$this->db->where()</dfn> function, enabling you to set the WHERE clause.
You can optionally pass this information directly into the update function as a string:</p>

<code>$this->db->update('mytable', $data, "id = 4");</code>

<p>Or as an array:</p>

<code>$this->db->update('mytable', $data, array('id' => $id));</code>

<p>You may also use the <dfn>$this->db->set()</dfn> function described above when performing updates.</p>

<h2>$this->db->update_batch();</h2>
<p>Generates an update string based on the data you supply, and runs the query. You can either pass an
<strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>

<code>
$data = array(<br/>
&nbsp;&nbsp;&nbsp;array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'My Name 2' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'My date 2'<br />
&nbsp;&nbsp;&nbsp;),<br />
&nbsp;&nbsp;&nbsp;array(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'Another title' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'Another Name 2' ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'Another date 2'<br />
&nbsp;&nbsp;&nbsp;)<br/>
);<br />
<br />
$this->db->update_batch('mytable', $data, 'title');
<br /><br />
// Produces: <br />
// UPDATE `mytable` SET `name` = CASE<br />
// WHEN `title` = 'My title' THEN 'My Name 2'<br />
// WHEN `title` = 'Another title' THEN 'Another Name 2'<br />
// ELSE `name` END,<br />
// `date` = CASE <br />
// WHEN `title` = 'My title' THEN 'My date 2'<br />
// WHEN `title` = 'Another title' THEN 'Another date 2'<br />
// ELSE `date` END<br />
// WHERE `title` IN ('My title','Another title')</code>

<p>The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.</p>

<p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>


<a name="delete">&nbsp;</a>
<h1>Deleting Data</h1>



<h2>$this->db->delete();</h2>
<p>Generates a delete SQL string and runs the query.</p>

<code>
$this->db->delete('mytable', array('id' => $id));
<br /><br />
// Produces:<br />
// DELETE FROM mytable <br />
// WHERE id = $id</code>

<p>The first parameter is the table name, the second is the where clause. You can also use the <dfn>where()</dfn> or <dfn>or_where()</dfn> functions instead of passing
the data to the second parameter of the function:</p>

<p><code> $this->db->where('id', $id);<br />
	$this->db->delete('mytable'); <br />
	<br />
	// Produces:<br />
	// DELETE FROM mytable <br />
	// WHERE id = $id</code></p>
<p>An array of table names can be passed into delete() if you would like to delete data from more than 1 table.</p>
<p><code>$tables = array('table1', 'table2', 'table3');<br />
$this-&gt;db-&gt;where('id', '5');<br />
$this-&gt;db-&gt;delete($tables);</code></p>
<p>If you want to delete all data from a table, you can use the <dfn>truncate()</dfn> function, or <dfn>empty_table()</dfn>.</p>
<h2>$this-&gt;db-&gt;empty_table();</h2>
<p>Generates a delete SQL string and runs the query.<code>	$this-&gt;db-&gt;empty_table('mytable'); <br />
	<br />
// Produces<br />
// DELETE FROM mytable</code></p>
<h2>$this-&gt;db-&gt;truncate();</h2>
<p>Generates a truncate SQL string and runs the query.</p>
<code> $this-&gt;db-&gt;from('mytable'); <br />
$this-&gt;db-&gt;truncate(); <br />
// or <br />
$this-&gt;db-&gt;truncate('mytable'); <br />
<br />
// Produce:<br />
// TRUNCATE mytable <br />
</code>
<p class="important"><strong>Note:</strong> If the TRUNCATE command isn't available, truncate() will execute as &quot;DELETE FROM table&quot;.</p>

<h1><a name="chaining">&nbsp;</a>Method Chaining</h1>

<p>Method chaining allows you to simplify your syntax by connecting multiple functions.  Consider this example:</p>

<code>
<dfn>$this->db</dfn><kbd>-></kbd><var>select</var>('title')<kbd>-></kbd><var>from</var>('mytable')<kbd>-></kbd><var>where</var>('id', $id)<kbd>-></kbd><var>limit</var>(10, 20);<br />
<br />
$query = $this->db->get();</code>

<p class="important"><strong>Note:</strong> Method chaining only works with PHP 5.</p>

<p>&nbsp;</p>

<h1><a name="caching">&nbsp;</a>Active Record Caching</h1>

<p>While not &quot;true&quot; caching, Active Record enables you to save (or &quot;cache&quot;) certain parts of your queries for reuse at a later point in your script's execution. Normally, when an Active Record call is completed, all stored information is reset for the next call. With caching, you can prevent this reset, and reuse information easily.</p>

<p>Cached calls are cumulative. If you make 2 cached select() calls, and then 2 uncached select() calls, this will result in 4 select() calls. There are three Caching functions available:</p>

<h2>$this-&gt;db-&gt;start_cache()</h2>

<p>This function must be called to begin caching. All Active Record queries of the correct type (see below for supported queries) are stored for later use.</p>

<h2>$this-&gt;db-&gt;stop_cache()</h2>

<p>This function can be called to stop caching.</p>

<h2>$this-&gt;db-&gt;flush_cache()</h2>

<p>This function deletes all items from the Active Record cache.</p>

<p>Here's a usage example:</p>

<p><code>$this-&gt;db-&gt;start_cache();<br />
$this-&gt;db-&gt;select('field1');<br />
$this-&gt;db-&gt;stop_cache();<br /><br />
$this-&gt;db-&gt;get('tablename');<br />
<br />
//Generates: SELECT `field1` FROM (`tablename`)<br />
<br />
$this-&gt;db-&gt;select('field2');<br />
$this-&gt;db-&gt;get('tablename');<br />
<br />
//Generates:  SELECT `field1`, `field2` FROM (`tablename`)<br />
<br />
$this-&gt;db-&gt;flush_cache();<br />
<br />
$this-&gt;db-&gt;select('field2');<br />
$this-&gt;db-&gt;get('tablename');<br />
<br />
//Generates:  SELECT `field2` FROM (`tablename`)</code></p>

<p class="important"> <strong>Note:</strong> The following statements can be cached: select, from, join, where, like, group_by, having, order_by, set</p>
<p>&nbsp;</p>
</div>
<!-- END CONTENT -->


<div id="footer">
<p>
Previous Topic:&nbsp;&nbsp;<a href="helpers.html">Query Helper Functions</a>
&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
Next Topic:&nbsp;&nbsp;<a href="transactions.html">Transactions</a>
</p>
<p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2012 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p>
</div>

</body>
</html>