CodeIgniter gives you access to a Query Builder class. This patternallows information to be retrieved, inserted, and updated in yourdatabase with minimal scripting. In some cases only one or two linesof code are necessary to perform a database action.CodeIgniter does not require that each database table be its own classfile. It instead provides a more simplified interface.
Beyond simplicity, a major benefit to using the Query Builder featuresis that it allows you to create database independent applications, sincethe query syntax is generated by each database adapter. It also allowsfor safer queries, since the values are escaped automatically by thesystem.
Codeigniter Insert multiple rows in db with a table form closed Ask Question -2. I've found similar questions but, I'm failing to find any answers that works for my situation. Using Codeigniter: I have a db table for products and a db table for inventory. I want to display an html table on my site, each row being a product. I've included. CodeIgniter User Guide. CodeIgniter User Guide Version 2.2.6. 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. It can be used instead of passing a data array directly to the insert or update functions.
Note
If you intend to write your own queries you can disable thisclass in your database config file, allowing the core database libraryand adapter to utilize fewer resources.
The following functions allow you to build SQL SELECT statements.
$this->db->get()
Runs the selection query and returns the result. Can be used by itselfto retrieve all records from a table:
The second and third parameters enable you to set a limit and offsetclause:
You’ll notice that the above function is assigned to a variable named$query, which can be used to show the results:
Please visit the result functions page for a fulldiscussion regarding result generation.
$this->db->get_compiled_select()
Compiles the selection query just like $this->db->get() but does not runthe query. This method simply returns the SQL query as a string.
Example:
The second parameter enables you to set whether or not the query builder querywill be reset (by default it will be reset, just like when using $this->db->get()):
The key thing to notice in the above example is that the second query did notutilize $this->db->from() and did not pass a table name into the firstparameter. The reason for this outcome is because the query has not beenexecuted using $this->db->get() which resets values or reset directlyusing $this->db->reset_query().
$this->db->get_where()
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:
Please read the about the where function below for more information.
Note
get_where() was formerly known as getwhere(), which has been removed
$this->db->select()
Permits you to write the SELECT portion of your query:
Note
If you are selecting all (*) from a table you do not need touse this function. When omitted, CodeIgniter assumes that you wishto select all fields and automatically adds ‘SELECT *’.
$this->db->select()
accepts an optional second parameter. If you set itto FALSE, CodeIgniter will not try to protect your field or table names.This is useful if you need a compound select statement where automaticescaping of fields may break them.
$this->db->select_max()
Writes a SELECTMAX(field)
portion for your query. You can optionallyinclude a second parameter to rename the resulting field.
$this->db->select_min()
Writes a “SELECT MIN(field)” portion for your query. As withselect_max(), You can optionally include a second parameter to renamethe resulting field.
$this->db->select_avg()
Writes a “SELECT AVG(field)” portion for your query. As withselect_max(), You can optionally include a second parameter to renamethe resulting field.
$this->db->select_sum()
Writes a “SELECT SUM(field)” portion for your query. As withselect_max(), You can optionally include a second parameter to renamethe resulting field.
$this->db->from()
Permits you to write the FROM portion of your query:
Note
As shown earlier, the FROM portion of your query can be specifiedin the $this->db->get() function, so use whichever method you prefer.
$this->db->join()
Permits you to write the JOIN portion of your query:
Multiple function calls can be made if you need several joins in onequery.
If you need a specific type of JOIN you can specify it via the thirdparameter of the function. Options are: left, right, outer, inner, leftouter, and right outer.
$this->db->where()
This function enables you to set WHERE clauses using one of fourmethods:
Note
All values passed to this function are escaped automatically,producing safer queries.
Simple key/value method:
Notice that the equal sign is added for you.
If you use multiple function calls they will be chained together withAND between them:
Custom key/value method:
You can include an operator in the first parameter in order tocontrol the comparison:
Associative array method:
You can include your own operators using this method as well:
- Custom string:
You can write your own clauses manually:
$this->db->where()
accepts an optional third parameter. If you set it toFALSE, CodeIgniter will not try to protect your field or table names.
$this->db->or_where()
This function is identical to the one above, except that multipleinstances are joined by OR:
Note
or_where() was formerly known as orwhere(), which has beenremoved.
$this->db->where_in()
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND ifappropriate
$this->db->or_where_in()
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR ifappropriate
$this->db->where_not_in()
Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined withAND if appropriate
$this->db->or_where_not_in()
Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined with ORif appropriate
$this->db->like()
This method enables you to generate LIKE clauses, useful for doingsearches.
Note
All values passed to this method are escaped automatically.
Simple key/value method:
If you use multiple method calls they will be chained together withAND between them:
If you want to control where the wildcard (%) is placed, you can usean optional third argument. Your options are ‘before’, ‘after’, ‘none’ and‘both’ (which is the default).
Associative array method:
$this->db->or_like()
This method is identical to the one above, except that multipleinstances are joined by OR:
Note
or_like()
was formerly known as orlike()
, which has been removed.
$this->db->not_like()
This method is identical to like()
, except that it generatesNOT LIKE statements:
$this->db->or_not_like()
This method is identical to not_like()
, except that multipleinstances are joined by OR:
$this->db->group_by()
Permits you to write the GROUP BY portion of your query:
You can also pass an array of multiple values as well:
Note
group_by() was formerly known as groupby(), which has beenremoved.
$this->db->distinct()
Adds the “DISTINCT” keyword to a query
$this->db->having()
Permits you to write the HAVING portion of your query. There are 2possible syntaxes, 1 argument or 2:
You can also pass an array of multiple values as well:
If you are using a database that CodeIgniter escapes queries for, youcan prevent escaping content by passing an optional third argument, andsetting it to FALSE.
$this->db->or_having()
Identical to having(), only separates multiple clauses with “OR”.
$this->db->order_by()
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 ASC, DESC AND RANDOM.
You can also pass your own string in the first parameter:
Or multiple function calls can be made if you need multiple fields.
If you choose the RANDOM direction option, then the first parameters willbe ignored, unless you specify a numeric seed value.
Note
order_by() was formerly known as orderby(), which has beenremoved.
Note
Random ordering is not currently supported in Oracle andwill default to ASC instead.
$this->db->limit()
Lets you limit the number of rows you would like returned by the query:
The second parameter lets you set a result offset.
$this->db->count_all_results()
Permits you to determine the number of rows in a particular ActiveRecord query. Queries will accept Query Builder restrictors such aswhere()
, or_where()
, like()
, or_like()
, etc. Example:
However, this method also resets any field values that you may have passedto select()
. If you need to keep them, you can pass FALSE
as thesecond parameter:
$this->db->count_all()
Permits you to determine the number of rows in a particular table.Submit the table name in the first parameter. Example:
Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allowyou to create queries with complex WHERE clauses. Nested groups are supported. Example:
Note
groups need to be balanced, make sure every group_start() is matched by a group_end().
$this->db->group_start()
Starts a new group by adding an opening parenthesis to the WHERE clause of the query.
$this->db->or_group_start()
Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘OR’.
$this->db->not_group_start()
Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘NOT’.
$this->db->or_not_group_start()
Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘OR NOT’.
$this->db->group_end()
Ends the current group by adding an closing parenthesis to the WHERE clause of the query.
$this->db->insert()
Generates an insert string based on the data you supply, and runs thequery. You can either pass an array or an object to thefunction. Here is an example using an array:
The first parameter will contain the table name, the second is anassociative array of values.
Here is an example using an object:
The first parameter will contain the table name, the second is anobject.
Note
All values are escaped automatically producing safer queries.
$this->db->get_compiled_insert()
Compiles the insertion query just like $this->db->insert() but does notrun the query. This method simply returns the SQL query as a string.
Example:
The second parameter enables you to set whether or not the query builder querywill be reset (by default it will be–just like $this->db->insert()):
The key thing to notice in the above example is that the second query did notutilize $this->db->from() nor did it pass a table name into the firstparameter. The reason this worked is because the query has not been executedusing $this->db->insert() which resets values or reset directly using$this->db->reset_query().
Note
This method doesn’t work for batched inserts.
$this->db->insert_batch()
Generates an insert string based on the data you supply, and runs thequery. You can either pass an array or an object to thefunction. Here is an example using an array:
The first parameter will contain the table name, the second is anassociative array of values.
Note
All values are escaped automatically producing safer queries.
$this->db->replace()
This method executes a REPLACE statement, which is basically the SQLstandard for (optional) DELETE + INSERT, using PRIMARY and UNIQUEkeys as the determining factor.In our case, it will save you from the need to implement complexlogics with different combinations of select()
, update()
,delete()
and insert()
calls.
Example:
In the above example, if we assume that the title field is our primarykey, then if a row containing ‘My title’ as the title value, that rowwill be deleted with our new row data replacing it.
Usage of the set()
method is also allowed and all fields areautomatically escaped, just like with insert()
.
$this->db->set()
This function enables you to set values for inserts or updates.
It can be used instead of passing a data array directly to the insertor update functions:
If you use multiple function called they will be assembled properlybased on whether you are doing an insert or an update:
set() will also accept an optional third parameter ($escape
), thatwill prevent data from being escaped if set to FALSE. To illustrate thedifference, here is set()
used both with and without the escapeparameter.
You can also pass an associative array to this function:
Or an object:
$this->db->update()
Generates an update string and runs the query based on the data yousupply. You can pass an array or an object to the function. Hereis an example using an array:
Or you can supply an object:
Note
All values are escaped automatically producing safer queries.
You’ll notice the use of the $this->db->where() function, enabling youto set the WHERE clause. You can optionally pass this informationdirectly into the update function as a string:
Or as an array:
You may also use the $this->db->set() function described above whenperforming updates.
$this->db->update_batch()
Generates an update string based on the data you supply, and runs the query.You can either pass an array or an object to the function.Here is an example using an array:
The first parameter will contain the table name, the second is an associativearray of values, the third parameter is the where key.
Note
All values are escaped automatically producing safer queries.
Note
affected_rows()
won’t give you proper results with this method,due to the very nature of how it works. Instead, update_batch()
returns the number of rows affected.
$this->db->get_compiled_update()
This works exactly the same way as $this->db->get_compiled_insert()
exceptthat it produces an UPDATE SQL string instead of an INSERT SQL string.
For more information view documentation for $this->db->get_compiled_insert().
$this->db->delete()
Generates a delete SQL string and runs the query.
The first parameter is the table name, the second is the where clause.You can also use the where() or or_where() functions instead of passingthe data to the second parameter of the function:
An array of table names can be passed into delete() if you would like todelete data from more than 1 table.
If you want to delete all data from a table, you can use the truncate()function, or empty_table().
$this->db->empty_table()
Generates a delete SQL string and runs thequery.:
$this->db->truncate()
Generates a truncate SQL string and runs the query.
Note
If the TRUNCATE command isn’t available, truncate() willexecute as “DELETE FROM table”.
$this->db->get_compiled_delete()
This works exactly the same way as $this->db->get_compiled_insert()
exceptthat it produces a DELETE SQL string instead of an INSERT SQL string.
For more information view documentation for $this->db->get_compiled_insert().
Method chaining allows you to simplify your syntax by connectingmultiple functions. Consider this example:
While not “true” caching, Query Builder enables you to save (or “cache”)certain parts of your queries for reuse at a later point in yourscript’s execution. Normally, when an Query Builder call is completed,all stored information is reset for the next call. With caching, you canprevent this reset, and reuse information easily.
Cached calls are cumulative. If you make 2 cached select() calls, andthen 2 uncached select() calls, this will result in 4 select() calls.There are three Caching functions available:
$this->db->start_cache()
This function must be called to begin caching. All Query Builder queriesof the correct type (see below for supported queries) are stored forlater use.
$this->db->stop_cache()
This function can be called to stop caching.
$this->db->flush_cache()
This function deletes all items from the Query Builder cache.
An example of caching¶
Here’s a usage example:
Note
The following statements can be cached: select, from, join,where, like, group_by, having, order_by
$this->db->reset_query()
Resetting Query Builder allows you to start fresh with your query withoutexecuting it first using a method like $this->db->get() or $this->db->insert().Just like the methods that execute a query, this will not reset items you’vecached using Query Builder Caching.
This is useful in situations where you are using Query Builder to generate SQL(ex. $this->db->get_compiled_select()
) but then choose to, for instance,run the query:
Note
Double calls to get_compiled_select()
while you’re using theQuery Builder Caching functionality and NOT resetting your querieswill results in the cache being merged twice. That in turn willi.e. if you’re caching a select()
- select the same field twice.
CI_DB_query_builder
¶reset_query
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Resets the current Query Builder state. Useful when you wantto build a query that can be cancelled under certain conditions.
start_cache
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Starts the Query Builder cache.
stop_cache
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Stops the Query Builder cache.
flush_cache
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Empties the Query Builder cache.
set_dbprefix
([$prefix = '])¶Parameters: |
|
---|---|
Returns: | The DB prefix in use |
Return type: | string |
Sets the database prefix, without having to reconnect.
dbprefix
([$table = '])¶Parameters: |
|
---|---|
Returns: | The prefixed table name |
Return type: | string |
Prepends a database prefix, if one exists in configuration.
count_all_results
([$table = '[, $reset = TRUE]])¶Parameters: |
|
---|---|
Returns: | Number of rows in the query result |
Return type: | int |
Generates a platform-specific query string that countsall records returned by an Query Builder query.
get
([$table = '[, $limit = NULL[, $offset = NULL]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_result instance (method chaining) |
Return type: | CI_DB_result |
Compiles and runs SELECT statement based on the alreadycalled Query Builder methods.
get_where
([$table = '[, $where = NULL[, $limit = NULL[, $offset = NULL]]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_result instance (method chaining) |
Return type: | CI_DB_result |
Same as get()
, but also allows the WHERE to be added directly.
select
([$select = '*'[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a SELECT clause to a query.
select_avg
([$select = '[, $alias = ']])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a SELECT AVG(field) clause to a query.
select_max
([$select = '[, $alias = ']])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a SELECT MAX(field) clause to a query.
select_min
([$select = '[, $alias = ']])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a SELECT MIN(field) clause to a query.
select_sum
([$select = '[, $alias = ']])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a SELECT SUM(field) clause to a query.
distinct
([$val = TRUE])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Sets a flag which tells the query builder to adda DISTINCT clause to the SELECT portion of the query.
from
($from)¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Specifies the FROM clause of a query.
join
($table, $cond[, $type = '[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a JOIN clause to a query.
where
($key[, $value = NULL[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates the WHERE portion of the query.Separates multiple calls with ‘AND’.
or_where
($key[, $value = NULL[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates the WHERE portion of the query.Separates multiple calls with ‘OR’.
or_where_in
([$key = NULL[, $values = NULL[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates a WHERE field IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.
or_where_not_in
([$key = NULL[, $values = NULL[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates a WHERE field NOT IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.
where_in
([$key = NULL[, $values = NULL[, $escape = NULL]]])¶![Insert 2 Tabel Codeigniter Insert 2 Tabel Codeigniter](https://i.ytimg.com/vi/3RofZ-BTCec/maxresdefault.jpg)
Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates a WHERE field IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.
where_not_in
([$key = NULL[, $values = NULL[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | DB_query_builder instance |
Return type: | object |
Generates a WHERE field NOT IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.
group_start
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Starts a group expression, using ANDs for the conditions inside it.
or_group_start
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Starts a group expression, using ORs for the conditions inside it.
not_group_start
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Starts a group expression, using AND NOTs for the conditions inside it.
or_not_group_start
()¶Returns: | CI_DB_query_builder instance (method chaining) |
---|---|
Return type: | CI_DB_query_builder |
Starts a group expression, using OR NOTs for the conditions inside it.
group_end
()¶Returns: | DB_query_builder instance |
---|---|
Return type: | object |
Ends a group expression.
like
($field[, $match = '[, $side = 'both'[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a LIKE clause to a query, separating multiple calls with AND.
or_like
($field[, $match = '[, $side = 'both'[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a LIKE clause to a query, separating multiple class with OR.
not_like
($field[, $match = '[, $side = 'both'[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a NOT LIKE clause to a query, separating multiple calls with AND.
or_not_like
($field[, $match = '[, $side = 'both'[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a NOT LIKE clause to a query, separating multiple calls with OR.
having
($key[, $value = NULL[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
![Codeigniter 2 docs Codeigniter 2 docs](https://i.ytimg.com/vi/tQEdXYj57yI/maxresdefault.jpg)
Adds a HAVING clause to a query, separating multiple calls with AND.
or_having
($key[, $value = NULL[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a HAVING clause to a query, separating multiple calls with OR.
group_by
($by[, $escape = NULL])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds a GROUP BY clause to a query.
order_by
($orderby[, $direction = '[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds an ORDER BY clause to a query.
limit
($value[, $offset = 0])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds LIMIT and OFFSET clauses to a query.
offset
($offset)¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds an OFFSET clause to a query.
set
($key[, $value = '[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds field/value pairs to be passed later to insert()
,update()
or replace()
.
insert
([$table = '[, $set = NULL[, $escape = NULL]]])¶Parameters: |
|
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
Compiles and executes an INSERT statement.
insert_batch
($table[, $set = NULL[, $escape = NULL[, $batch_size = 100]]])¶Parameters: |
|
---|---|
Returns: | Number of rows inserted or FALSE on failure |
Return type: | mixed |
Compiles and executes batch INSERT
statements.
Note
When more than $batch_size
rows are provided, multipleINSERT
queries will be executed, each trying to insertup to $batch_size
rows.
set_insert_batch
($key[, $value = '[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds field/value pairs to be inserted in a table later via insert_batch()
.
update
([$table = '[, $set = NULL[, $where = NULL[, $limit = NULL]]]])¶Parameters: |
|
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
Compiles and executes an UPDATE statement.
update_batch
($table[, $set = NULL[, $value = NULL[, $batch_size = 100]]])¶Parameters: |
|
---|---|
Returns: | Number of rows updated or FALSE on failure |
Return type: | mixed |
Compiles and executes batch UPDATE
statements.
Note
When more than $batch_size
field/value pairs are provided,multiple queries will be executed, each handling up to$batch_size
field/value pairs.
set_update_batch
($key[, $value = '[, $escape = NULL]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) |
Return type: | CI_DB_query_builder |
Adds field/value pairs to be updated in a table later via update_batch()
.
replace
([$table = '[, $set = NULL]])¶Parameters: |
|
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
Compiles and executes a REPLACE statement.
delete
([$table = '[, $where = '[, $limit = NULL[, $reset_data = TRUE]]]])¶Parameters: |
|
---|---|
Returns: | CI_DB_query_builder instance (method chaining) or FALSE on failure |
Return type: | mixed |
Compiles and executes a DELETE query.
truncate
([$table = '])¶Parameters: |
|
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
Executes a TRUNCATE statement on a table.
Note
If the database platform in use doesn’t support TRUNCATE,a DELETE statement will be used instead.
empty_table
([$table = '])¶Parameters: |
|
---|---|
Returns: | TRUE on success, FALSE on failure |
Return type: | bool |
Deletes all records from a table via a DELETE statement.
get_compiled_select
([$table = '[, $reset = TRUE]])¶Parameters: |
|
---|---|
Returns: | The compiled SQL statement as a string |
Return type: | string |
Compiles a SELECT statement and returns it as a string.
get_compiled_insert
([$table = '[, $reset = TRUE]])¶Parameters: |
|
---|---|
Returns: | The compiled SQL statement as a string |
Return type: | string |
Compiles an INSERT statement and returns it as a string.
get_compiled_update
([$table = '[, $reset = TRUE]])¶Parameters: |
|
---|---|
Returns: | The compiled SQL statement as a string |
Return type: | string |
Compiles an UPDATE statement and returns it as a string.
get_compiled_delete
([$table = '[, $reset = TRUE]])¶Parameters: |
|
---|---|
Returns: | The compiled SQL statement as a string |
Return type: | string |
Compiles a DELETE statement and returns it as a string.
Data is the bloodline of most applications. The data needs to be stored in such a way that it can be further analyzed to provide insights and facilitate business decisions. The data is usually stored in the database. Among the chief concerns when interacting with the database is security, ease of access and database vendor specific implementations of Structured Query Language (SQL).
Active record is a design pattern that makes it easy to interact with the database in ease, secure and eloquent way.
The active record has the following advantages
- Insert, update and delete records with simple method chains of active record
- Submits the user input in a secure way using parameters
- Allows you to work with multiple database engines such as MySQL, SQL Server, etc. without rewriting the application code
- CodeIgniter uses drivers specific for each database engine in the background.
In this tutorial, you will learn:
How to use Active Record: Example
In this tutorial, we will discuss the tutorial database. We will have two tables, one with orders the other with details.
This tutorial assumes you have MySQL database installed up and running.
Run the following scripts to create tutorial database:
The above code creates a database named ci_active_record and creates two tables namely orders and order_details. The relationship between the two tables is defined by the column id in orders and order_id in order_details table.
CodeIgniter Database Configuration
We will now configure our application to be able to communicate with this database.
Open database configuration file located in application/config/database.php
locate the following lines in the configuration file
Update the above code to the following
Note: you will need to replace the username and password to the ones that match your configuration of MySQL.
In addition to the database configuration details, we also need to tell CodeIgniter to load the database library when it loads
Step 1) Open the following file application/config/autoload.php
Step 2) Locate the $autoload array key libraries and load the database library as shown below
HERE,
- The above code loads the database library when the application starts
CodeIgniter Insert Active Record
For testing purposes, we will create a controller and defined routes that we will be using to interact with our application via active record.
Create a new file application/controllers/ActiveRecordController.php
Add the following code to ActiveRecordController.php
HERE,
- $data = […] defines an array variable data that uses database table names as array keys and assigns values to them
- $this->db->insert('orders', $data); calls the insert method of the database library, passes in the table name orders and the array variable $data as the parameter. This line generates the SQL INSERT statement using the array keys as the field names and the array values as the values to be inserted into the database.
Now that we have successfully created the controller method for active record, we will now need to create a route that we will call to execute the controller method.
Now open routes.php in application/config/routes.php
add the following line to the routes
HERE,
- We define a route ar/insert that calls the store_order of the ActiveRecordController.
Let's now start the web server to test our method.
Run the following command to start the built-in server for PHP
HERE,
- The above command browser to the command line and start the built-in server at port 3000.
Load the following URL into your browser
You will get the following results
Open the MySQL tutorial database and check the orders table
You will able to newly created row as shown in the image below
CodeIgniter Select Active Record
In this section, we will see how to read the records that we have in the database and display them in the web browser as an unordered list
Add the following method to the ActiveRecordController
HERE,
- $query = $this->db->get('orders'); runs the select query against the orders table selecting all the fields
- echo '<h4>Orders Listing</h4>'; displays a HTML heading of size 3
- echo '<ul>'; prints the opening tag for un-ordered HTML list
- foreach ($query->result() as $row) {…} used the for loop to loop through the results returned from the database. echo '<li>$row->customer_name</li>'; prints the customer_name from the database
Before you load the following URL, you can load a couple more records to the database.
Lets now define a route for the SELECT query
Open application/config/routes.php table
Add the following route
HERE,
- The route ar points to the index method of ActiveRecordController class. This is by default that's why we didn't specify the index method as you did for the route that inserts records
Assuming the web server is already running, load the following URL
You should be able to see results which is very much similar to the following in your web browser
CodeIgniter Update Active Record
In this section, we will tal about how to use the active record to update the database. Let's say we want to update the customer name Joe Thomas to Joe.
Add the following method to ActiveRecordController class
HERE,
- $data = […] defines the fields and values that we wish to update in the database table
- $this->db->where('id', 1); sets the where clause of the update query
- $this->db->update('orders', $data); generates the SQL update query and executes it against our database.
The above code will produce the following SQL statement
Let's now update the routes.php application/config/routes.php
Add the following route
Save the changes
Load the following URL in the web browser
Let's now display the database records and see if the changes have been affected.
As you can see from the above-given Image, the first record has been updated from Joe Thomas to Joe.
CodeIgniter Delete Active Record
We will now delete a record from the database. We will delete the record with the id of 3.
Add the following method to the ActiveRecordController
HERE,
- $this->db->where('id', 1); sets the where clause
- $this->db->delete('orders'); deletes the database row in orders table based on the criteria set using the where clause.
To execute the above code, load the following URL in our web browser
Summary
In this tutorial, you have learned how to work with an active record to insert, update, delete and select records from the database. We worked with static values to create records, update and delete. In the next tutorial, we will create a user interface that the user can use to create records dynamically in the database.