faa13b3e747f96798f7684929eb872177a728cf2
[living-lab-site.git] / user_guide / database / active_record.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
3 <head>
4
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <title>Active Record : CodeIgniter User Guide</title>
7
8 <style type='text/css' media='all'>@import url('../userguide.css');</style>
9 <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
10
11 <script type="text/javascript" src="../nav/nav.js"></script>
12 <script type="text/javascript" src="../nav/prototype.lite.js"></script>
13 <script type="text/javascript" src="../nav/moo.fx.js"></script>
14 <script type="text/javascript" src="../nav/user_guide_menu.js"></script>
15
16 <meta http-equiv='expires' content='-1' />
17 <meta http-equiv= 'pragma' content='no-cache' />
18 <meta name='robots' content='all' />
19 <meta name='author' content='ExpressionEngine Dev Team' />
20 <meta name='description' content='CodeIgniter User Guide' />
21 </head>
22 <body>
23
24 <!-- START NAVIGATION -->
25 <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
26 <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>
27 <div id="masthead">
28 <table cellpadding="0" cellspacing="0" border="0" style="width:100%">
29 <tr>
30 <td><h1>CodeIgniter User Guide Version 2.0.2</h1></td>
31 <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
32 </tr>
33 </table>
34 </div>
35 <!-- END NAVIGATION -->
36
37
38 <!-- START BREADCRUMB -->
39 <table cellpadding="0" cellspacing="0" border="0" style="width:100%">
40 <tr>
41 <td id="breadcrumb">
42 <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
43 <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
44 <a href="index.html">Database Library</a> &nbsp;&#8250;&nbsp;
45 Active Record
46 </td>
47 <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/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>
48 </tr>
49 </table>
50 <!-- END BREADCRUMB -->
51
52 <br clear="all" />
53
54 <!-- START CONTENT -->
55 <div id="content">
56
57 <h1>Active Record Class</h1>
58
59 <p>CodeIgniter uses a modified version of the Active Record Database Pattern.
60 This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting.
61 In some cases only one or two lines of code are necessary to perform a database action.
62 CodeIgniter does not require that each database table be its own class file.  It instead provides a more simplified interface.</p>
63
64 <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
65 is generated by each database adapter.  It also allows for safer queries, since the values are escaped automatically by the system.</p>
66
67 <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>
68
69 <ul>
70 <li><a href="#select">Selecting Data</a></li>
71 <li><a href="#insert">Inserting Data</a></li>
72 <li><a href="#update">Updating Data</a></li>
73 <li><a href="#delete">Deleting Data</a></li>
74 <li><a href="#chaining">Method Chaining</a></li>
75 <li><a href="#caching">Active Record Caching</a></li>
76 </ul>
77
78 <h1><a name="select">&nbsp;</a>Selecting Data</h1>
79
80 <p>The following functions allow you to build SQL <strong>SELECT</strong> statements.</p>
81
82 <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>
83
84
85 <h2>$this->db->get();</h2>
86
87 <p>Runs the selection query and returns the result.  Can be used by itself to retrieve all records from a table:</p>
88
89 <code>$query = $this->db->get('mytable');<br />
90 <br />
91 // Produces: SELECT * FROM mytable</code>
92
93 <p>The second and third parameters enable you to set a limit and offset clause:</p>
94
95 <code>$query = $this->db->get('mytable', 10, 20);<br />
96 <br />
97 // Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)</code>
98
99 <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>
100
101 <code>$query = $this->db->get('mytable');<br />
102 <br />
103 foreach ($query->result() as $row)<br />
104 {<br />
105 &nbsp;&nbsp;&nbsp;&nbsp;echo $row->title;<br />
106 }</code>
107
108 <p>Please visit the <a href="results.html">result functions</a> page for a full discussion regarding result generation.</p>
109
110
111 <h2>$this->db->get_where();</h2>
112
113 <p>Identical to the above function except that it permits you to add a "where" clause in the second parameter,
114 instead of using the db->where() function:</p>
115
116 <code>$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);</code>
117
118 <p>Please read the about the where function below for more information.</p>
119 <p class="important">Note: get_where() was formerly known as getwhere(), which has been removed</p>
120
121 <h2>$this->db->select();</h2>
122 <p>Permits you to write the SELECT portion of your query:</p>
123 <p><code>
124 $this->db->select('title, content, date');<br />
125 <br />
126 $query = $this->db->get('mytable');<br />
127 <br />
128 // Produces: SELECT title, content, date FROM mytable</code></p>
129 <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>
130
131 <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>
132 <p><code>$this-&gt;db-&gt;select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); <br />
133 $query = $this-&gt;db-&gt;get('mytable');<br />
134 </code></p>
135 <h2>$this->db->select_max();</h2>
136 <p>Writes a "SELECT MAX(field)" portion for your query. You can optionally include a second parameter to rename the resulting field.</p>
137 <p><code>
138 $this->db->select_max('age');<br />
139 $query = $this->db->get('members');<br />
140
141 // Produces: SELECT MAX(age) as age FROM members<br />
142 <br />
143 $this-&gt;db-&gt;select_max('age', 'member_age');<br />
144 $query = $this-&gt;db-&gt;get('members');<br />
145 // Produces: SELECT MAX(age) as member_age FROM members</code></p>
146
147 <h2>$this->db->select_min();</h2>
148 <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>
149 <p><code>
150 $this->db->select_min('age');<br />
151 $query = $this->db->get('members');<br />
152 // Produces: SELECT MIN(age) as age FROM members</code></p>
153
154 <h2>$this->db->select_avg();</h2>
155 <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>
156 <p><code>
157 $this->db->select_avg('age');<br />
158 $query = $this->db->get('members');<br />
159 // Produces: SELECT AVG(age) as age FROM members</code></p>
160
161 <h2>$this->db->select_sum();</h2>
162 <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>
163 <p><code>
164 $this->db->select_sum('age');<br />
165 $query = $this->db->get('members');<br />
166 // Produces: SELECT SUM(age) as age FROM members</code></p>
167
168 <h2>$this->db->from();</h2>
169
170 <p>Permits you to write the FROM portion of your query:</p>
171
172 <code>
173 $this->db->select('title, content, date');<br />
174 $this->db->from('mytable');<br />
175 <br />
176 $query = $this->db->get();<br />
177 <br />
178 // Produces: SELECT title, content, date FROM mytable</code>
179
180 <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
181 you prefer.</p>
182
183 <h2>$this->db->join();</h2>
184
185 <p>Permits you to write the JOIN portion of your query:</p>
186
187 <code>
188 $this->db->select('*');<br />
189 $this->db->from('blogs');<br />
190 $this->db->join('comments', 'comments.id = blogs.id');<br />
191 <br />
192 $query = $this->db->get();<br />
193 <br />
194 // Produces: <br />
195 // SELECT * FROM blogs<br />
196 // JOIN comments ON comments.id = blogs.id<br />
197 </code>
198
199 <p>Multiple function calls can be made if you need several joins in one query.</p>
200
201 <p>If you need a specific type of JOIN you can specify it via the third parameter of the function.
202 Options are: left, right, outer, inner, left outer, and right outer.</p>
203
204 <code>
205 $this->db->join('comments', 'comments.id = blogs.id', <strong>'left'</strong>);<br />
206 <br />
207 // Produces: LEFT JOIN comments ON comments.id = blogs.id</code>
208
209
210
211
212
213 <h2>$this->db->where();</h2>
214 <p>This function enables you to set <strong>WHERE</strong> clauses using one of four methods:</p>
215
216 <p class="important"><strong>Note:</strong> All values passed to this function are escaped automatically, producing safer queries.</p>
217
218 <ol>
219         <li><strong>Simple key/value method:</strong>
220
221         <code>$this->db->where('name', $name);
222         <br /><br />// Produces: WHERE name = 'Joe'     </code>
223
224         <p>Notice that the equal sign is added for you.</p>
225
226         <p>If you use multiple function calls they will be chained together with <var>AND</var> between them:</p>
227
228         <code>$this->db->where('name', $name);<br />
229         $this->db->where('title', $title);<br />
230         $this->db->where('status', $status);
231         <br /><br />// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'      </code> </li>
232
233         <li><strong>Custom key/value method:</strong>
234
235         <p>You can include an operator in the first parameter in order to control the comparison:</p>
236
237         <code>$this->db->where('name !=', $name);<br />
238         $this->db->where('id <', $id);
239         <br /><br />// Produces: WHERE name != 'Joe' AND id < 45        </code> </li>
240         <li><strong>Associative array method:</strong>
241
242
243         <code>
244         $array = array('name' => $name, 'title' => $title, 'status' => $status);<br /><br />
245
246         $this->db->where($array);
247         <br /><br />// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'    </code>
248
249         <p>You can include your own operators using this method as well:</p>
250
251         <code>
252         $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);<br /><br />
253
254         $this->db->where($array);</code>        </li>
255                 <li><strong>Custom string:</strong>
256
257                 <p>You can write your own clauses manually:</p>
258
259                 <code>
260                 $where = "name='Joe' AND status='boss' OR status='active'";<br /><br />
261                 $this->db->where($where);</code></li>
262         </ol>
263
264
265 <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>
266 <p><code>               $this-&gt;db-&gt;where('MATCH (field) AGAINST (&quot;value&quot;)', NULL, FALSE);<br />
267 </code></p>
268 <h2>$this->db->or_where();</h2>
269 <p>This function is identical to the one above, except that multiple instances are joined by OR:</p>
270
271 <code>
272 $this->db->where('name !=', $name);<br />
273 $this->db->or_where('id >', $id);
274 <br />
275 <br />// Produces: WHERE name != 'Joe' OR id > 50</code>
276
277 <p class="important">Note: or_where() was formerly known as orwhere(), which has been removed.</p>
278
279
280 <h2>$this->db->where_in();</h2>
281 <p>Generates a WHERE field IN ('item', 'item') SQL query joined with  AND if appropriate</p>
282 <p><code>
283         $names = array('Frank', 'Todd', 'James');<br />
284         $this->db->where_in('username', $names);<br />
285         // Produces: WHERE username IN ('Frank', 'Todd', 'James')</code></p>
286
287 <h2>$this->db->or_where_in();</h2>
288 <p>Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate</p>
289 <p><code>
290         $names = array('Frank', 'Todd', 'James');<br />
291         $this->db->or_where_in('username', $names);<br />
292         // Produces: OR username IN ('Frank', 'Todd', 'James')</code></p>
293
294 <h2>$this->db->where_not_in();</h2>
295 <p>Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate</p>
296 <p><code>
297         $names = array('Frank', 'Todd', 'James');<br />
298         $this->db->where_not_in('username', $names);<br />
299         // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')</code></p>
300
301 <h2>$this->db->or_where_not_in();</h2>
302 <p>Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate</p>
303 <p><code>
304         $names = array('Frank', 'Todd', 'James');<br />
305         $this->db->or_where_not_in('username', $names);<br />
306         // Produces: OR username NOT IN ('Frank', 'Todd', 'James')</code></p>
307
308 <h2>$this->db->like();</h2>
309 <p>This function enables you to generate <strong>LIKE</strong> clauses, useful for doing searches.</p>
310
311 <p class="important"><strong>Note:</strong> All values passed to this function are escaped automatically.</p>
312
313
314 <ol>
315         <li><strong>Simple key/value method:</strong>
316
317         <code>$this->db->like('title', 'match');
318         <br /><br />// Produces: WHERE title LIKE '%match%'     </code>
319
320         <p>If you use multiple function calls they will be chained together with <var>AND</var> between them:</p>
321
322         <code>$this->db->like('title', 'match');<br />
323         $this->db->like('body', 'match');
324         <br /><br />
325         // WHERE title LIKE '%match%' AND  body LIKE '%match%</code>
326         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).
327         <code>$this->db->like('title', 'match', 'before');
328         <br />
329                 // Produces: WHERE title LIKE '%match'  <br />
330                 <br />
331         $this-&gt;db-&gt;like('title', 'match', 'after'); <br />
332 // Produces: WHERE title LIKE 'match%' <br />
333 <br />
334         $this-&gt;db-&gt;like('title', 'match', 'both'); <br />
335 // Produces: WHERE title LIKE '%match%' </code> </li>
336
337         <li><strong>Associative array method:</strong>
338
339         <code>
340         $array = array('title' => $match, 'page1' => $match, 'page2' => $match);<br /><br />
341
342         $this->db->like($array);
343         <br /><br />// WHERE title LIKE '%match%' AND  page1 LIKE '%match%' AND  page2 LIKE '%match%'</code></li>
344         </ol>
345
346
347 <h2>$this->db->or_like();</h2>
348 <p>This function is identical to the one above, except that multiple instances are joined by OR:</p>
349
350 <code>
351 $this->db->like('title', 'match');<br />
352 $this->db->or_like('body', $match);
353 <br />
354 <br />// WHERE title LIKE '%match%' OR  body LIKE '%match%'</code>
355
356
357
358
359 <p class="important">Note: or_like() was formerly known as orlike(), which has been removed.</p>
360 <h2>$this-&gt;db-&gt;not_like();</h2>
361 <p>This function is identical to <strong>like()</strong>, except that it generates NOT LIKE statements:</p>
362 <code> $this-&gt;db-&gt;not_like('title', 'match');<br />
363 <br />
364 // WHERE title NOT LIKE '%match%</code>
365 <h2>$this-&gt;db-&gt;or_not_like();</h2>
366 <p>This function is identical to <strong>not_like()</strong>, except that multiple instances are joined by OR:</p>
367 <code> $this-&gt;db-&gt;like('title', 'match');<br />
368 $this-&gt;db-&gt;or_not_like('body', 'match'); <br />
369 <br />
370 // WHERE title  LIKE '%match% OR body NOT LIKE '%match%'</code>
371 <h2>$this->db->group_by();</h2>
372 <p>Permits you to write the GROUP BY portion of your query:</p>
373
374 <code>$this->db->group_by("title");
375 <br /><br />// Produces: GROUP BY title
376 </code>
377
378 <p>You can also pass an array of multiple values as well:</p>
379
380 <code>$this->db->group_by(array("title", "date"));
381 <br />
382 <br />// Produces: GROUP BY title, date</code>
383
384 <p class="important">Note: group_by() was formerly known as groupby(), which has been removed. </p>
385
386 <h2> $this-&gt;db-&gt;distinct();<br />
387 </h2>
388 <p>Adds the &quot;DISTINCT&quot; keyword to  a query</p>
389 <p><code>$this-&gt;db-&gt;distinct();<br />
390         $this-&gt;db-&gt;get('table');<br />
391                 <br />
392         // Produces: SELECT DISTINCT * FROM table</code></p>
393 <h2>$this->db->having();</h2>
394 <p>Permits you to write the HAVING portion of your query. There are 2 possible syntaxes, 1 argument or 2:</p>
395
396 <code>$this->db->having('user_id = 45');
397 <br />
398 // Produces: HAVING user_id = 45<br />
399 <br />
400 $this-&gt;db-&gt;having('user_id',  45); <br />
401 // Produces: HAVING user_id = 45<br />
402 <br />
403 </code>
404
405 <p>You can also pass an array of multiple values as well:</p>
406
407
408 <p><code>$this->db->having(array('title =' => 'My Title', 'id <' => $id)); <br />
409                 <br />
410         // Produces: HAVING title = 'My Title', id < 45</code></p>
411 <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>
412 <p><code>$this-&gt;db-&gt;having('user_id',  45); <br />
413 // Produces: HAVING `user_id` = 45 in some databases such as MySQL
414                 <br />
415                 $this-&gt;db-&gt;having('user_id',  45, FALSE); <br />
416 // Produces: HAVING user_id = 45</code></p>
417 <h2>$this-&gt;db-&gt;or_having();</h2>
418 <p>Identical to having(), only separates multiple clauses with &quot;OR&quot;.</p>
419 <h2>$this->db->order_by();</h2>
420 <p>Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by.
421 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>
422
423 <code>$this->db->order_by("title", "desc");
424 <br />
425 <br />// Produces: ORDER BY title DESC
426 </code>
427
428 <p>You can also pass your own string in the first parameter:</p>
429
430 <code>$this->db->order_by('title desc, name asc');
431 <br />
432 <br />// Produces: ORDER BY title DESC, name ASC
433 </code>
434
435 <p>Or multiple function calls can be made if you need multiple fields.</p>
436
437 <p><code>$this->db->order_by("title", "desc");<br />
438         $this->db->order_by("name", "asc"); <br />
439         <br />
440         // Produces: ORDER BY title DESC, name ASC
441         </code></p>
442 <p class="important">Note: order_by() was formerly known as orderby(), which has been removed.</p>
443 <p class="important">Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to 'ASC'.</p>
444 <h2>$this->db->limit();</h2>
445 <p>Lets you limit the number of rows you would like returned by the query:</p>
446
447 <code>
448 $this->db->limit(10);<br />
449 <br />
450 // Produces: LIMIT 10</code>
451
452
453 <p>The second parameter lets you set a result offset.</p>
454
455 <code>
456 $this->db->limit(10, 20);<br />
457 <br />
458 // Produces: LIMIT 20, 10 (in MySQL.  Other databases have slightly different syntax)</code>
459
460
461 <h2>$this->db->count_all_results();</h2>
462
463 <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>
464 <code>echo $this->db->count_all_results('<var>my_table</var>');<br />
465
466 // Produces an integer, like 25<br />
467 <br />
468 $this-&gt;db-&gt;like('title', 'match');<br />
469 $this-&gt;db-&gt;from('<var>my_table</var>');<br />
470 echo $this-&gt;db-&gt;count_all_results();<br />
471 // Produces an integer, like 17 </code>
472
473 <h2>$this->db->count_all();</h2>
474
475 <p>Permits you to determine the number of rows in a particular table.  Submit the table name in the first parameter. Example:</p>
476
477 <code>echo $this->db->count_all('<var>my_table</var>');<br />
478 <br />
479 // Produces an integer, like 25</code>
480
481
482
483 <a name="insert">&nbsp;</a>
484 <h1>Inserting Data</h1>
485
486 <h2>$this->db->insert();</h2>
487 <p>Generates an insert string based on the data you supply, and runs the query. You can either pass an
488 <strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>
489
490 <code>
491 $data = array(<br />
492 &nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
493 &nbsp;&nbsp;&nbsp;'name' => 'My Name' ,<br />
494 &nbsp;&nbsp;&nbsp;'date' => 'My date'<br />
495 );<br />
496 <br />
497 $this->db->insert('mytable', $data);
498 <br /><br />
499 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')</code>
500
501 <p>The first parameter will contain the table name, the second is an associative array of values.</p>
502
503 <p>Here is an example using an object:</p>
504
505 <code>
506 /*<br />
507 &nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
508 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
509 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
510 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
511 &nbsp;&nbsp;&nbsp;&nbsp;}<br />
512 */<br />
513 <br />
514 $object = new Myclass;<br />
515 <br />
516 $this->db->insert('mytable', $object);
517 <br /><br />
518 // Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')</code>
519
520 <p>The first parameter will contain the table name, the second is an object.</p>
521
522 <p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>
523
524 <h2>$this->db->insert_batch();</h2>
525 <p>Generates an insert string based on the data you supply, and runs the query. You can either pass an
526 <strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>
527
528 <code>
529 $data = array(<br/>
530 &nbsp;&nbsp;&nbsp;array(<br />
531 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
532 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'My Name' ,<br />
533 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'My date'<br />
534 &nbsp;&nbsp;&nbsp;),<br />
535 &nbsp;&nbsp;&nbsp;array(<br />
536 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'Another title' ,<br />
537 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'Another Name' ,<br />
538 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'Another date'<br />
539 &nbsp;&nbsp;&nbsp;)<br/>
540 );<br />
541 <br />
542 $this->db->insert_batch('mytable', $data);
543 <br /><br />
544 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')</code>
545
546 <p>The first parameter will contain the table name, the second is an associative array of values.</p>
547
548 <h2>$this->db->insert_batch();</h2>
549 <p>Generates an insert string based on the data you supply, and runs the query. You can either pass an
550 <strong>array</strong> or an <strong>object</strong> to the function.  Here is an example using an array:</p>
551
552 <code>
553 $data = array(<br/>
554 &nbsp;&nbsp;&nbsp;array(<br />
555 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'My title' ,<br />
556 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'My Name' ,<br />
557 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'My date'<br />
558 &nbsp;&nbsp;&nbsp;),<br />
559 &nbsp;&nbsp;&nbsp;array(<br />
560 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => 'Another title' ,<br />
561 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => 'Another Name' ,<br />
562 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => 'Another date'<br />
563 &nbsp;&nbsp;&nbsp;)<br/>
564 );<br />
565 <br />
566 $this->db->update_batch('mytable', $data);
567 <br /><br />
568 // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')</code>
569
570 <p>The first parameter will contain the table name, the second is an associative array of values.</p>
571
572 <p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>
573
574
575
576 <h2>$this->db->set();</h2>
577 <p>This function enables you to set values for <dfn>inserts</dfn> or <dfn>updates</dfn>.</p>
578
579 <p><strong>It can be used instead of passing a data array directly to the insert or update functions:</strong> </p>
580
581 <code>$this->db->set('name', $name);
582 <br />
583 $this->db->insert('mytable');
584 <br /><br />
585 // Produces: INSERT INTO mytable (name) VALUES ('{$name}')</code>
586
587 <p>If you use multiple function called they will be assembled properly based on whether you are doing an insert or an update:</p>
588
589 <code>$this-&gt;db-&gt;set('name', $name);<br />
590 $this-&gt;db-&gt;set('title', $title);<br />
591 $this-&gt;db-&gt;set('status', $status);<br />
592 $this-&gt;db-&gt;insert('mytable'); </code>
593 <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>
594 <p><code>$this-&gt;db-&gt;set('field', 'field+1', FALSE);<br />
595         $this-&gt;db-&gt;insert('mytable'); <br />
596         // gives INSERT INTO mytable (field) VALUES (field+1)<br />
597         <br />
598         $this-&gt;db-&gt;set('field', 'field+1');<br />
599         $this-&gt;db-&gt;insert('mytable'); <br />
600         // gives INSERT INTO mytable (field) VALUES ('field+1')</code></p>
601 <p>You can also pass an associative array to this function:</p>
602 <code>
603 $array = array('name' => $name, 'title' => $title, 'status' => $status);<br /><br />
604
605 $this->db->set($array);<br />
606 $this->db->insert('mytable');
607 </code>
608
609 <p>Or an object:</p>
610
611
612 <code>
613 /*<br />
614 &nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
615 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
616 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
617 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
618 &nbsp;&nbsp;&nbsp;&nbsp;}<br />
619 */<br />
620 <br />
621 $object = new Myclass;<br />
622 <br />
623 $this->db->set($object);<br />
624 $this->db->insert('mytable');
625 </code>
626
627
628
629 <a name="update">&nbsp;</a>
630 <h1>Updating Data</h1>
631
632 <h2>$this->db->update();</h2>
633 <p>Generates an update string and runs the query based on the data you supply.  You can pass an
634 <strong>array</strong> or an <strong>object</strong> to the function. Here is an example using
635 an array:</p>
636
637 <code>
638 $data = array(<br />
639 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'title' => $title,<br />
640 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'name' => $name,<br />
641 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'date' => $date<br />
642 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br />
643 <br />
644 $this->db->where('id', $id);<br />
645 $this->db->update('mytable', $data);
646 <br /><br />
647 // Produces:<br />
648 // UPDATE mytable <br />
649 // SET title = '{$title}', name = '{$name}', date = '{$date}'<br />
650 // WHERE id = $id</code>
651
652 <p>Or you can supply an object:</p>
653
654 <code>
655 /*<br />
656 &nbsp;&nbsp;&nbsp;&nbsp;class Myclass {<br />
657 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $title = 'My Title';<br />
658 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $content = 'My Content';<br />
659 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var  $date = 'My Date';<br />
660 &nbsp;&nbsp;&nbsp;&nbsp;}<br />
661 */<br />
662 <br />
663 $object = new Myclass;<br />
664 <br />
665 $this->db->where('id', $id);<br />
666 $this->db->update('mytable', $object);
667 <br />
668 <br />
669 // Produces:<br />
670 // UPDATE mytable <br />
671 // SET title = '{$title}', name = '{$name}', date = '{$date}'<br />
672 // WHERE id = $id</code>
673
674
675
676 <p class="important"><strong>Note:</strong> All values are escaped automatically producing safer queries.</p>
677
678 <p>You'll notice the use of the <dfn>$this->db->where()</dfn> function, enabling you to set the WHERE clause.
679 You can optionally pass this information directly into the update function as a string:</p>
680
681 <code>$this->db->update('mytable', $data, "id = 4");</code>
682
683 <p>Or as an array:</p>
684
685 <code>$this->db->update('mytable', $data, array('id' => $id));</code>
686
687 <p>You may also use the <dfn>$this->db->set()</dfn> function described above when performing updates.</p>
688
689
690 <a name="delete">&nbsp;</a>
691 <h1>Deleting Data</h1>
692
693
694
695 <h2>$this->db->delete();</h2>
696 <p>Generates a delete SQL string and runs the query.</p>
697
698 <code>
699 $this->db->delete('mytable', array('id' => $id));
700 <br /><br />
701 // Produces:<br />
702 // DELETE FROM mytable <br />
703 // WHERE id = $id</code>
704
705 <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
706 the data to the second parameter of the function:</p>
707
708 <p><code> $this->db->where('id', $id);<br />
709         $this->db->delete('mytable'); <br />
710         <br />
711         // Produces:<br />
712         // DELETE FROM mytable <br />
713         // WHERE id = $id</code></p>
714 <p>An array of table names can be passed into delete() if you would like to delete data from more than 1 table.</p>
715 <p><code>$tables = array('table1', 'table2', 'table3');<br />
716 $this-&gt;db-&gt;where('id', '5');<br />
717 $this-&gt;db-&gt;delete($tables);</code></p>
718 <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>
719 <h2>$this-&gt;db-&gt;empty_table();</h2>
720 <p>Generates a delete SQL string and runs the query.<code>      $this-&gt;db-&gt;empty_table('mytable'); <br />
721         <br />
722 // Produces<br />
723 // DELETE FROM mytable</code></p>
724 <h2>$this-&gt;db-&gt;truncate();</h2>
725 <p>Generates a truncate SQL string and runs the query.</p>
726 <code> $this-&gt;db-&gt;from('mytable'); <br />
727 $this-&gt;db-&gt;truncate(); <br />
728 // or <br />
729 $this-&gt;db-&gt;truncate('mytable'); <br />
730 <br />
731 // Produce:<br />
732 // TRUNCATE mytable <br />
733 </code>
734 <p class="important"><strong>Note:</strong> If the TRUNCATE command isn't available, truncate() will execute as &quot;DELETE FROM table&quot;.</p>
735
736 <h1><a name="chaining">&nbsp;</a>Method Chaining</h1>
737
738 <p>Method chaining allows you to simplify your syntax by connecting multiple functions.  Consider this example:</p>
739
740 <code>
741 <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 />
742 <br />
743 $query = $this->db->get();</code>
744
745 <p class="important"><strong>Note:</strong> Method chaining only works with PHP 5.</p>
746
747 <p>&nbsp;</p>
748
749 <h1><a name="caching">&nbsp;</a>Active Record Caching</h1>
750
751 <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>
752
753 <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>
754
755 <h2>$this-&gt;db-&gt;start_cache()</h2>
756
757 <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>
758
759 <h2>$this-&gt;db-&gt;stop_cache()</h2>
760
761 <p>This function can be called to stop caching.</p>
762
763 <h2>$this-&gt;db-&gt;flush_cache()</h2>
764
765 <p>This function deletes all items from the Active Record cache.</p>
766
767 <p>Here's a usage example:</p>
768
769 <p><code>$this-&gt;db-&gt;start_cache();<br />
770 $this-&gt;db-&gt;select('field1');<br />
771 $this-&gt;db-&gt;stop_cache();<br /><br />
772 $this-&gt;db-&gt;get('tablename');<br />
773 <br />
774 //Generates: SELECT `field1` FROM (`tablename`)<br />
775 <br />
776 $this-&gt;db-&gt;select('field2');<br />
777 $this-&gt;db-&gt;get('tablename');<br />
778 <br />
779 //Generates:  SELECT `field1`, `field2` FROM (`tablename`)<br />
780 <br />
781 $this-&gt;db-&gt;flush_cache();<br />
782 <br />
783 $this-&gt;db-&gt;select('field2');<br />
784 $this-&gt;db-&gt;get('tablename');<br />
785 <br />
786 //Generates:  SELECT `field2` FROM (`tablename`)</code></p>
787
788 <p class="important"> <strong>Note:</strong> The following statements can be cached: select, from, join, where, like, group_by, having, order_by, set</p>
789 <p>&nbsp;</p>
790 </div>
791 <!-- END CONTENT -->
792
793
794 <div id="footer">
795 <p>
796 Previous Topic:&nbsp;&nbsp;<a href="helpers.html">Query Helper Functions</a>
797 &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
798 <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
799 <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
800 Next Topic:&nbsp;&nbsp;<a href="transactions.html">Transactions</a>
801 </p>
802 <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2011 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p>
803 </div>
804
805 </body>
806 </html>