blob: 710ababb0d9d339bcda02454442997dd00115a83 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001#######
2Queries
3#######
4
James L Parryd980e332014-11-24 16:16:40 -08005************
6Query Basics
7************
Derek Jones8ede1a22011-10-05 13:34:52 -05008
James L Parryd980e332014-11-24 16:16:40 -08009Regular Queries
10===============
11
12To submit a query, use the **query** function::
Derek Jones8ede1a22011-10-05 13:34:52 -050013
14 $this->db->query('YOUR QUERY HERE');
15
16The query() function returns a database result **object** when "read"
17type queries are run, which you can use to :doc:`show your
18results <results>`. When "write" type queries are run it simply
19returns TRUE or FALSE depending on success or failure. When retrieving
20data you will typically assign the query to your own variable, like
21this::
22
23 $query = $this->db->query('YOUR QUERY HERE');
24
James L Parryd980e332014-11-24 16:16:40 -080025Simplified Queries
26==================
Derek Jones8ede1a22011-10-05 13:34:52 -050027
James L Parryd980e332014-11-24 16:16:40 -080028The **simple_query** method is a simplified version of the
29$this->db->query() method. It DOES
Andrey Andreev1922a882012-06-15 15:16:51 +030030NOT return a database result set, nor does it set the query timer, or
31compile bind data, or store your query for debugging. It simply lets you
32submit a query. Most users will rarely use this function.
33
34It returns whatever the database drivers' "execute" function returns.
35That typically is TRUE/FALSE on success or failure for write type queries
36such as INSERT, DELETE or UPDATE statements (which is what it really
37should be used for) and a resource/object on success for queries with
38fetchable results.
39
40::
41
42 if ($this->db->simple_query('YOUR QUERY'))
43 {
44 echo "Success!";
45 }
46 else
47 {
48 echo "Query failed!";
49 }
50
Andrey Andreev8c833f42014-05-14 13:32:34 +030051.. note:: PostgreSQL's ``pg_exec()`` function (for example) always
52 returns a resource on success, even for write type queries.
53 So take that in mind if you're looking for a boolean value.
Derek Jones8ede1a22011-10-05 13:34:52 -050054
55***************************************
56Working with Database prefixes manually
57***************************************
58
59If you have configured a database prefix and would like to prepend it to
60a table name for use in a native SQL query for example, then you can use
61the following::
62
63 $this->db->dbprefix('tablename'); // outputs prefix_tablename
64
65
66If for any reason you would like to change the prefix programatically
67without needing to create a new connection, you can use this method::
68
Andrey Andreeve8eb8672017-09-16 17:27:29 +030069 $this->db->set_dbprefix('newprefix_');
Joseph Wensleyf24f4042011-10-06 22:53:29 -040070 $this->db->dbprefix('tablename'); // outputs newprefix_tablename
Derek Jones8ede1a22011-10-05 13:34:52 -050071
72
73**********************
74Protecting identifiers
75**********************
76
77In many databases it is advisable to protect table and field names - for
Jamie Rumbelow7efad202012-02-19 12:37:00 +000078example with backticks in MySQL. **Query Builder queries are
Derek Jones8ede1a22011-10-05 13:34:52 -050079automatically protected**, however if you need to manually protect an
80identifier you can use::
81
82 $this->db->protect_identifiers('table_name');
83
Andrey Andreev8c833f42014-05-14 13:32:34 +030084.. important:: Although the Query Builder will try its best to properly
85 quote any field and table names that you feed it, note that it
86 is NOT designed to work with arbitrary user input. DO NOT feed it
87 with unsanitized user data.
Derek Jones8ede1a22011-10-05 13:34:52 -050088
89This function will also add a table prefix to your table, assuming you
90have a prefix specified in your database config file. To enable the
Kit Sundeed2f95c2014-05-15 16:20:19 +080091prefixing set TRUE (boolean) via the second parameter::
Derek Jones8ede1a22011-10-05 13:34:52 -050092
93 $this->db->protect_identifiers('table_name', TRUE);
94
95
96****************
97Escaping Queries
98****************
99
100It's a very good security practice to escape your data before submitting
101it into your database. CodeIgniter has three methods that help you do
102this:
103
104#. **$this->db->escape()** This function determines the data type so
105 that it can escape only string data. It also automatically adds
106 single quotes around the data so you don't have to:
107 ::
108
109 $sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
110
111#. **$this->db->escape_str()** This function escapes the data passed to
112 it, regardless of type. Most of the time you'll use the above
113 function rather than this one. Use the function like this:
114 ::
115
116 $sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
117
118#. **$this->db->escape_like_str()** This method should be used when
119 strings are to be used in LIKE conditions so that LIKE wildcards
120 ('%', '\_') in the string are also properly escaped.
121
122::
123
James L Parry8252b752014-11-24 17:26:58 -0800124 $search = '20% raise';
125 $sql = "SELECT id FROM table WHERE column LIKE '%" .
Andrey Andreev86d2ec42016-02-17 19:19:56 +0200126 $this->db->escape_like_str($search)."%' ESCAPE '!'";
127
128.. important:: The ``escape_like_str()`` method uses '!' (exclamation mark)
129 to escape special characters for *LIKE* conditions. Because this
130 method escapes partial strings that you would wrap in quotes
131 yourself, it cannot automatically add the ``ESCAPE '!'``
132 condition for you, and so you'll have to manually do that.
Derek Jones8ede1a22011-10-05 13:34:52 -0500133
134
135**************
136Query Bindings
137**************
138
139Bindings enable you to simplify your query syntax by letting the system
140put the queries together for you. Consider the following example::
141
Joseph Wensleyf24f4042011-10-06 22:53:29 -0400142 $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
143 $this->db->query($sql, array(3, 'live', 'Rick'));
Derek Jones8ede1a22011-10-05 13:34:52 -0500144
145The question marks in the query are automatically replaced with the
146values in the array in the second parameter of the query function.
147
clawoo1db369f2014-10-22 19:10:55 +0300148Binding also work with arrays, which will be transformed to IN sets::
clawooff8bff12014-10-21 10:41:02 +0300149
150 $sql = "SELECT * FROM some_table WHERE id IN ? AND status = ? AND author = ?";
151 $this->db->query($sql, array(array(3, 6), 'live', 'Rick'));
152
clawoo1db369f2014-10-22 19:10:55 +0300153The resulting query will be::
154
155 SELECT * FROM some_table WHERE id IN (3,6) AND status = 'live' AND author = 'Rick'
clawooff8bff12014-10-21 10:41:02 +0300156
Derek Jones8ede1a22011-10-05 13:34:52 -0500157The secondary benefit of using binds is that the values are
158automatically escaped, producing safer queries. You don't have to
159remember to manually escape data; the engine does it automatically for
160you.
Andrey Andreev4be5de12012-03-02 15:45:41 +0200161
162***************
163Handling Errors
164***************
165
James L Parryd980e332014-11-24 16:16:40 -0800166**$this->db->error();**
Andrey Andreev4be5de12012-03-02 15:45:41 +0200167
Andrey Andreev71d8f722017-01-17 12:01:00 +0200168If you need to get the last error that has occurred, the error() method
Andrey Andreev4be5de12012-03-02 15:45:41 +0200169will return an array containing its code and message. Here's a quick
170example::
171
172 if ( ! $this->db->simple_query('SELECT `example_field` FROM `example_table`'))
173 {
174 $error = $this->db->error(); // Has keys 'code' and 'message'
175 }
176