8/20/2019 Insert 2 Tabel Codeigniter
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.
Insert Database -CRUD 2 -Codeigniter 3. Posted on August 14, 2016 by hasta. Insert Database -CRUD 2 -Codeigniter 3: Pengaturan Awal: 1. Database /MySQL (menggunakan database tutorial sebelumnya) 2. Config Database. Android Library (2) Android Table (2) ArcGIS (5) Codeiginter Login (2). In CodeIgniter, insert method is used to insert record in database table. In order to generate insert statement, insert method can be used in following ways – Syntax.
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.
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.
$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.
$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 as
where() , 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.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |