The insert ID number when performing database inserts.
+
Note: If using the PDO driver with PostgreSQL, this function requires a $name parameter, which specifies the appropriate sequence to check for the insert id.
$this->db->affected_rows()
Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).
Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).
-
Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the
-correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file.
+
Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file.
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
@@ -666,6 +666,41 @@ You can optionally pass this information directly into the update function as a
You may also use the $this->db->set() function described above when performing 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:
+// Produces:
+// UPDATE `mytable` SET `name` = CASE
+// WHEN `title` = 'My title' THEN 'My Name 2'
+// WHEN `title` = 'Another title' THEN 'Another Name 2'
+// ELSE `name` END,
+// `date` = CASE
+// WHEN `title` = 'My title' THEN 'My date 2'
+// WHEN `title` = 'Another title' THEN 'Another date 2'
+// ELSE `date` END
+// WHERE `title` IN ('My title','Another title')
+
+
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
+
+
Note: All values are escaped automatically producing safer queries.
+
Deleting Data
--
cgit v1.2.3-24-g4f1b
From 19277f05c20a3de4beaebcac722659a0ed30a374 Mon Sep 17 00:00:00 2001
From: Adrian Macneil
Date: Thu, 22 Sep 2011 11:17:58 -0700
Subject: Documented third $after_field parameter of dbforge->add_column()
---
user_guide/database/forge.html | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'user_guide/database')
diff --git a/user_guide/database/forge.html b/user_guide/database/forge.html
index 6b8709892..528d1a24c 100644
--- a/user_guide/database/forge.html
+++ b/user_guide/database/forge.html
@@ -201,6 +201,10 @@ already be running, since the forge class relies on it.
CodeIgniter uses a modified version of the Active Record Database Pattern.
-This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting.
-In some cases only one or two lines of code are necessary to perform a database action.
-CodeIgniter does not require that each database table be its own class file. It instead provides a more simplified interface.
-
-
Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax
-is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.
-
-
Note: 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.
Please visit the result functions page for a full discussion regarding result generation.
-
-
-
$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:
-
-$this->db->select('title, content, date');
-
-$query = $this->db->get('mytable');
-
-// Produces: SELECT title, content, date FROM mytable
-
Note: If you are selecting all (*) from a table you do not need to use this function. When omitted, CodeIgniter assumes you wish to SELECT *
-
-
$this->db->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.
-
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
-$query = $this->db->get('mytable');
-
-
$this->db->select_max();
-
Writes a "SELECT MAX(field)" portion for your query. You can optionally include a second parameter to rename the resulting field.
-
-$this->db->select_max('age');
-$query = $this->db->get('members');
-
-// Produces: SELECT MAX(age) as age FROM members
-
-$this->db->select_max('age', 'member_age');
-$query = $this->db->get('members');
-// Produces: SELECT MAX(age) as member_age FROM members
-
-
$this->db->select_min();
-
Writes a "SELECT MIN(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
-
-$this->db->select_min('age');
-$query = $this->db->get('members');
-// Produces: SELECT MIN(age) as age FROM members
-
-
$this->db->select_avg();
-
Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
-
-$this->db->select_avg('age');
-$query = $this->db->get('members');
-// Produces: SELECT AVG(age) as age FROM members
-
-
$this->db->select_sum();
-
Writes a "SELECT SUM(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
-
-$this->db->select_sum('age');
-$query = $this->db->get('members');
-// Produces: SELECT SUM(age) as age FROM members
-
-
$this->db->from();
-
-
Permits you to write the FROM portion of your query:
Multiple function calls can be made if you need several joins in one query.
-
-
If you need a specific type of JOIN you can specify it via the third parameter of the function.
-Options are: left, right, outer, inner, left outer, and right outer.
-
-
- $where = "name='Joe' AND status='boss' OR status='active'";
- $this->db->where($where);
-
-
-
-
$this->db->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.
-
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
-
-
$this->db->or_where();
-
This function is identical to the one above, except that multiple instances are joined by OR:
-
-
-$this->db->where('name !=', $name);
-$this->db->or_where('id >', $id);
-
- // Produces: WHERE name != 'Joe' OR id > 50
-
-
Note: or_where() was formerly known as orwhere(), which has been removed.
-
-
-
$this->db->where_in();
-
Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate
-
- $names = array('Frank', 'Todd', 'James');
- $this->db->where_in('username', $names);
- // Produces: WHERE username IN ('Frank', 'Todd', 'James')
-
-
$this->db->or_where_in();
-
Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate
-
- $names = array('Frank', 'Todd', 'James');
- $this->db->or_where_in('username', $names);
- // Produces: OR username IN ('Frank', 'Todd', 'James')
-
-
$this->db->where_not_in();
-
Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate
-
- $names = array('Frank', 'Todd', 'James');
- $this->db->where_not_in('username', $names);
- // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')
-
-
$this->db->or_where_not_in();
-
Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate
-
- $names = array('Frank', 'Todd', 'James');
- $this->db->or_where_not_in('username', $names);
- // Produces: OR username NOT IN ('Frank', 'Todd', 'James')
-
-
$this->db->like();
-
This function enables you to generate LIKE clauses, useful for doing searches.
-
-
Note: All values passed to this function are escaped automatically.
- // WHERE title LIKE '%match%' AND body LIKE '%match%
- 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).
- $this->db->like('title', 'match', 'before');
-
- // Produces: WHERE title LIKE '%match'
-
- $this->db->like('title', 'match', 'after');
-// Produces: WHERE title LIKE 'match%'
-
- $this->db->like('title', 'match', 'both');
-// Produces: WHERE title LIKE '%match%'
-
-If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.
-
-
- $this->db->like('title', 'match', 'none');
-// Produces: WHERE title LIKE 'match'
-
-
-
You can also pass an array of multiple values as well:
-
-
-
$this->db->having(array('title =' => 'My Title', 'id <' => $id));
-
- // Produces: HAVING title = 'My Title', id < 45
-
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.
-
$this->db->having('user_id', 45);
-// Produces: HAVING `user_id` = 45 in some databases such as MySQL
-
- $this->db->having('user_id', 45, FALSE);
-// Produces: HAVING user_id = 45
-
$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 or desc, or random.
-
-$this->db->order_by("title", "desc");
-
- // Produces: ORDER BY title DESC
-
-
-
You can also pass your own string in the first parameter:
-
-$this->db->order_by('title desc, name asc');
-
- // Produces: ORDER BY title DESC, name ASC
-
-
-
Or multiple function calls can be made if you need multiple fields.
-
-
$this->db->order_by("title", "desc");
- $this->db->order_by("name", "asc");
-
- // Produces: ORDER BY title DESC, name ASC
-
-
Note: order_by() was formerly known as orderby(), which has been removed.
-
Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to 'ASC'.
-
$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->limit(10, 20);
-
-// Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
-
-
-
$this->db->count_all_results();
-
-
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:
-echo $this->db->count_all_results('my_table');
-
-// Produces an integer, like 25
-
-$this->db->like('title', 'match');
-$this->db->from('my_table');
-echo $this->db->count_all_results();
-// Produces an integer, like 17
-
-
$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:
-
-echo $this->db->count_all('my_table');
-
-// Produces an integer, like 25
-
-
-
-
-
Inserting Data
-
-
$this->db->insert();
-
Generates an insert 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 object.
-
-
Note: All values are escaped automatically producing safer queries.
-
-
$this->db->insert_batch();
-
Generates an insert 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:
set() 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.
-
-
-
-/*
- class Myclass {
- var $title = 'My Title';
- var $content = 'My Content';
- var $date = 'My Date';
- }
-*/
-
-$object = new Myclass;
-
-$this->db->set($object);
-$this->db->insert('mytable');
-
-
-
-
-
-
Updating Data
-
-
$this->db->update();
-
Generates an update string and runs the query based on the data you supply. You can pass an
-array or an object to the function. Here is an example using
-an array:
-// Produces:
-// UPDATE mytable
-// SET title = '{$title}', name = '{$name}', date = '{$date}'
-// WHERE id = $id
-
-
Or you can supply an object:
-
-
-/*
- class Myclass {
- var $title = 'My Title';
- var $content = 'My Content';
- var $date = 'My Date';
- }
-*/
-
-$object = new Myclass;
-
-$this->db->where('id', $id);
-$this->db->update('mytable', $object);
-
-
-// Produces:
-// UPDATE mytable
-// SET title = '{$title}', name = '{$name}', date = '{$date}'
-// WHERE id = $id
-
-
-
-
Note: All values are escaped automatically producing safer queries.
-
-
You'll notice the use of the $this->db->where() function, enabling you to set the WHERE clause.
-You can optionally pass this information directly into the update function as a string:
You may also use the $this->db->set() function described above when performing 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:
-// Produces:
-// UPDATE `mytable` SET `name` = CASE
-// WHEN `title` = 'My title' THEN 'My Name 2'
-// WHEN `title` = 'Another title' THEN 'Another Name 2'
-// ELSE `name` END,
-// `date` = CASE
-// WHEN `title` = 'My title' THEN 'My date 2'
-// WHEN `title` = 'Another title' THEN 'Another date 2'
-// ELSE `date` END
-// WHERE `title` IN ('My title','Another title')
-
-
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
-
-
Note: All values are escaped automatically producing safer queries.
-// Produces:
-// DELETE FROM mytable
-// WHERE id = $id
-
-
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 passing
-the data to the second parameter of the function:
-
-
$this->db->where('id', $id);
- $this->db->delete('mytable');
-
- // Produces:
- // DELETE FROM mytable
- // WHERE id = $id
-
An array of table names can be passed into delete() if you would like to delete data from more than 1 table.
While not "true" caching, Active Record enables you to save (or "cache") 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.
-
-
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:
-
-
$this->db->start_cache()
-
-
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.
-
-
$this->db->stop_cache()
-
-
This function can be called to stop caching.
-
-
$this->db->flush_cache()
-
-
This function deletes all items from the Active Record cache.
The Database Caching Class permits you to cache your queries as text files for reduced database load.
-
-
Important: This class is initialized automatically by the database driver
-when caching is enabled. Do NOT load this class manually.
-
-Also note: Not all query result functions are available when you use caching. Please read this page carefully.
-
-
Enabling Caching
-
-
Caching is enabled in three steps:
-
-
-
Create a writable directory on your server where the cache files can be stored.
-
Set the path to your cache folder in your application/config/database.php file.
-
Enable the caching feature, either globally by setting the preference in your application/config/database.php file, or manually as described below.
-
-
-
Once enabled, caching will happen automatically whenever a page is loaded that contains database queries.
-
-
-
How Does Caching Work?
-
-
CodeIgniter's query caching system happens dynamically when your pages are viewed.
-When caching is enabled, the first time a web page is loaded, the query result object will
-be serialized and stored in a text file on your server. The next time the page is loaded the cache file will be used instead of
-accessing your database. Your database usage can effectively be reduced to zero for any pages that have been cached.
-
-
Only read-type (SELECT) queries can be cached, since these are the only type of queries that produce a result.
-Write-type (INSERT, UPDATE, etc.) queries, since they don't generate a result, will not be cached by the system.
-
-
Cache files DO NOT expire. Any queries that have been cached will remain cached until you delete them. The caching system
-permits you clear caches associated with individual pages, or you can delete the entire collection of cache files.
-Typically you'll want to use the housekeeping functions described below to delete cache files after certain
-events take place, like when you've added new information to your database.
-
-
Will Caching Improve Your Site's Performance?
-
-
Getting a performance gain as a result of caching depends on many factors.
-If you have a highly optimized database under very little load, you probably won't see a performance boost.
-If your database is under heavy use you probably will see an improved response, assuming your file-system is not
-overly taxed. Remember that caching simply changes how your information is retrieved, shifting it from being a database
-operation to a file-system one.
-
-
In some clustered server environments, for example, caching may be detrimental since file-system operations are so intense.
-On single servers in shared environments, caching will probably be beneficial. Unfortunately there is no
-single answer to the question of whether you should cache your database. It really depends on your situation.
-
-
How are Cache Files Stored?
-
-
CodeIgniter places the result of EACH query into its own cache file. Sets of cache files are further organized into
-sub-folders corresponding to your controller functions. To be precise, the sub-folders are named identically to the
-first two segments of your URI (the controller class name and function name).
-
-
For example, let's say you have a controller called blog with a function called comments that
-contains three queries. The caching system will create a cache folder
-called blog+comments, into which it will write three cache files.
-
-
If you use dynamic queries that change based on information in your URI (when using pagination, for example), each instance of
-the query will produce its own cache file. It's possible, therefore, to end up with many times more cache files than you have
-queries.
-
-
-
Managing your Cache Files
-
-
Since cache files do not expire, you'll need to build deletion routines into your application. For example, let's say you have a blog
-that allows user commenting. Whenever a new comment is submitted you'll want to delete the cache files associated with the
-controller function that serves up your comments. You'll find two delete functions described below that help you
-clear data.
-
-
-
Not All Database Functions Work with Caching
-
-
Lastly, we need to point out that the result object that is cached is a simplified version of the full result object. For that reason,
-some of the query result functions are not available for use.
-
-
The following functions ARE NOT available when using a cached result object:
-
-
-
num_fields()
-
field_names()
-
field_data()
-
free_result()
-
-
-
Also, the two database resources (result_id and conn_id) are not available when caching, since result resources only
-pertain to run-time operations.
-
-
-
-
-
Function Reference
-
-
-
-
$this->db->cache_on() / $this->db->cache_off()
-
-
Manually enables/disables caching. This can be useful if you want to
-keep certain queries from being cached. Example:
-
-
-// Turn caching on
-$this->db->cache_on();
-$query = $this->db->query("SELECT * FROM mytable");
-
-// Turn caching off for this one query
-$this->db->cache_off();
-$query = $this->db->query("SELECT * FROM members WHERE member_id = '$current_user'");
-
-// Turn caching back on
-$this->db->cache_on();
-$query = $this->db->query("SELECT * FROM another_table");
-
-
-
-
$this->db->cache_delete()
-
-
Deletes the cache files associated with a particular page. This is useful if you need to clear caching after you update your database.
-
-
The caching system saves your cache files to folders that correspond to the URI of the page you are viewing. For example, if you are viewing
-a page at example.com/index.php/blog/comments, the caching system will put all cache files associated with it in a folder
-called blog+comments. To delete those particular cache files you will use:
This function enables you to call PHP database functions that are not natively included in CodeIgniter, in a platform independent manner.
-For example, lets say you want to call the mysql_get_client_info() function, which is not natively supported
-by CodeIgniter. You could do so like this:
-
You must supply the name of the function, without the mysql_ prefix, in the first parameter. The prefix is added
-automatically based on which database driver is currently being used. This permits you to run the same function on different database platforms.
-Obviously not all function calls are identical between platforms, so there are limits to how useful this function can be in terms of portability.
-
-
Any parameters needed by the function you are calling will be added to the second parameter.
CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.).
-The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php it the respective environment config folder.
-
-
The config settings are stored in a multi-dimensional array with this prototype:
The reason we use a multi-dimensional array rather than a more simple one is to permit you to optionally store
-multiple sets of connection values. If, for example, you run multiple environments (development, production, test, etc.)
-under a single installation, you can set up a connection group for each, then switch between groups as needed.
-For example, to set up a "test" environment you would do this:
Then, to globally tell the system to use that group you would set this variable located in the config file:
-
-$active_group = "test";
-
-
Note: The name "test" is arbitrary. It can be anything you want. By default we've used the word "default"
-for the primary connection, but it too can be renamed to something more relevant to your project.
-
-
Active Record
-
-
The Active Record Class is globally enabled or disabled by setting the $active_record variable in the database configuration file to TRUE/FALSE (boolean). If you are not using the active record class, setting it to FALSE will utilize fewer resources when the database classes are initialized.
-
-$active_record = TRUE;
-
-
Note: that some CodeIgniter classes such as Sessions require Active Records be enabled to access certain functionality.
-
-
Explanation of Values:
-
-
-
hostname - The hostname of your database server. Often this is "localhost".
-
username - The username used to connect to the database.
-
password - The password used to connect to the database.
-
database - The name of the database you want to connect to.
-
dbdriver - The database type. ie: mysql, postgres, odbc, etc. Must be specified in lower case.
-
dbprefix - An optional table prefix which will added to the table name when running Active Record queries. This permits multiple CodeIgniter installations to share one database.
-
pconnect - TRUE/FALSE (boolean) - Whether to use a persistent connection.
-
db_debug - TRUE/FALSE (boolean) - Whether database errors should be displayed.
-
cache_on - TRUE/FALSE (boolean) - Whether database query caching is enabled, see also Database Caching Class.
-
cachedir - The absolute server path to your database query cache directory.
-
char_set - The character set used in communicating with the database.
-
dbcollat - The character collation used in communicating with the database.
Note: For MySQL and MySQLi databases, this setting is only used as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 (and in table creation queries made with DB Forge). There is an incompatibility in PHP with mysql_real_escape_string() which can make your site vulnerable to SQL injection if you are using a multi-byte character set and are running versions lower than these. Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
-
swap_pre - A default table prefix that should be swapped with dbprefix. This is useful for distributed applications where you might run manually written queries, and need the prefix to still be customizable by the end user.
-
autoinit - Whether or not to automatically connect to the database when the library loads. If set to false, the connection will take place prior to executing the first query.
-
stricton - TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL while developing an application.
-
port - The database port number. To use this value you have to add a line to the database config array.$db['default']['port'] = 5432;
-
-
-
Note: Depending on what database platform you are using (MySQL, Postgres, etc.)
-not all values will be needed. For example, when using SQLite you will not need to supply a username or password, and
-the database name will be the path to your database file. The information above assumes you are using MySQL.
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/user_guide/database/connecting.html b/user_guide/database/connecting.html
deleted file mode 100644
index b18088132..000000000
--- a/user_guide/database/connecting.html
+++ /dev/null
@@ -1,190 +0,0 @@
-
-
-
-
-
-Connecting to your Database : CodeIgniter User Guide
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
The "auto connect" feature will load and instantiate the database class with every page load.
-To enable "auto connecting", add the word database to the library array, as indicated in the following file:
-
-
application/config/autoload.php
-
-
Manually Connecting
-
-
If only some of your pages require database connectivity you can manually connect to your database by adding this
-line of code in any function where it is needed, or in your class constructor to make the database
-available globally in that class.
-
-$this->load->database();
-
-
If the above function does not contain any information in the first parameter it will connect
-to the group specified in your database config file. For most people, this is the preferred method of use.
-
-
Available Parameters
-
-
-
The database connection values, passed either as an array or a DSN string.
-
TRUE/FALSE (boolean). Whether to return the connection ID (see Connecting to Multiple Databases below).
-
TRUE/FALSE (boolean). Whether to enable the Active Record class. Set to TRUE by default.
-
-
-
-
Manually Connecting to a Database
-
-
The first parameter of this function can optionally be used to specify a particular database group
-from your config file, or you can even submit connection values for a database that is not specified in your config file.
-Examples:
-
-
To choose a specific group from your config file you can do this:
-
-$this->load->database('group_name');
-
-
Where group_name is the name of the connection group from your config file.
-
-
-
To connect manually to a desired database you can pass an array of values:
Note: Change the words "group_one" and "group_two" to the specific group names you are connecting to (or
-you can pass the connection values as indicated above).
-
-
By setting the second parameter to TRUE (boolean) the function will return the database object.
-
-
-
When you connect this way, you will use your object name to issue commands rather than the syntax used throughout this guide. In other words, rather than issuing commands with:
-
-
$this->db->query(); $this->db->result(); etc...
-
-
You will instead use:
-
-
$DB1->query(); $DB1->result(); etc...
-
-
-
-
Reconnecting / Keeping the Connection Alive
-
-
If the database server's idle timeout is exceeded while you're doing some heavy PHP lifting (processing an image, for instance), you should consider pinging the server by using the reconnect() method before sending further queries, which can gracefully keep the connection alive or re-establish it.
-
-$this->db->reconnect();
-
-
Manually closing the Connection
-
-
While CodeIgniter intelligently takes care of closing your database connections, you can explicitly close the connection.
The following page contains example code showing how the database class is used. For complete details please
-read the individual pages describing each function.
-
-
-
Initializing the Database Class
-
-
The following code loads and initializes the database class based on your configuration settings:
-
-$this->load->database();
-
-
Once loaded the class is ready to be used as described below.
-
-
Note: If all your pages require database access you can connect automatically. See the connecting page for details.
-
-
-
Standard Query With Multiple Results (Object Version)
The above get() function retrieves all the results from the supplied table.
-The Active Record class contains a full compliment of functions
-for working with data.
There are several things you may wish to do when creating tables. Add fields, add keys to the table, alter columns. CodeIgniter provides a mechanism for this.
-
Adding fields
-
Fields are created via an associative array. Within the array you must include a 'type' key that relates to the datatype of the field. For example, INT, VARCHAR, TEXT, etc. Many datatypes (for example VARCHAR) also require a 'constraint' key.
-
$fields = array(
- 'users' => array(
- 'type' => 'VARCHAR',
- 'constraint' => '100',
- ),
- );
-
-// will translate to "users VARCHAR(100)" when the field is added.
-
Additionally, the following key/values can be used:
-
-
unsigned/true : to generate "UNSIGNED" in the field definition.
-
default/value : to generate a default value in the field definition.
-
null/true : to generate "NULL" in the field definition. Without this, the field will default to "NOT NULL".
-
auto_increment/true : generates an auto_increment flag on the field. Note that the field type must be a type that supports this, such as integer.
After the fields have been defined, they can be added using $this->dbforge->add_field($fields); followed by a call to the create_table() function.
-
$this->dbforge->add_field()
-
The add fields function will accept the above array.
-
Passing strings as fields
-
If you know exactly how you want a field to be created, you can pass the string into the field definitions with add_field()
-
$this->dbforge->add_field("label varchar(100) NOT NULL DEFAULT 'default label'");
-
Note: Multiple calls to add_field() are cumulative.
-
Creating an id field
-
There is a special exception for creating id fields. A field with type id will automatically be assinged as an INT(9) auto_incrementing Primary Key.
-
$this->dbforge->add_field('id');
- // gives id INT(9) NOT NULL AUTO_INCREMENT
-
Adding Keys
-
Generally speaking, you'll want your table to have Keys. This is accomplished with $this->dbforge->add_key('field'). An optional second parameter set to TRUE will make it a primary key. Note that add_key() must be followed by a call to create_table().
-
Multiple column non-primary keys must be sent as an array. Sample output below is for MySQL.
An optional second parameter set to TRUE adds an "IF NOT EXISTS" clause into the definition
-
$this->dbforge->create_table('table_name', TRUE);
-// gives CREATE TABLE IF NOT EXISTS table_name
-
Dropping a table
-
Executes a DROP TABLE sql
-
$this->dbforge->drop_table('table_name');
- // gives DROP TABLE IF EXISTS table_name
-
Renaming a table
-
Executes a TABLE rename
-
$this->dbforge->rename_table('old_table_name', 'new_table_name');
- // gives ALTER TABLE old_table_name RENAME TO new_table_name
-
Modifying Tables
-
$this->dbforge->add_column()
-
The add_column() function is used to modify an existing table. It accepts the same field array as above, and can be used for an unlimited number of additional fields.
The usage of this function is identical to add_column(), except it alters an existing column rather than adding a new one. In order to change the name you can add a "name" key into the field defining array.
The insert ID number when performing database inserts.
-
Note: If using the PDO driver with PostgreSQL, this function requires a $name parameter, which specifies the appropriate sequence to check for the insert id.
-
-
$this->db->affected_rows()
-
Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).
-
Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file.
-
-
-
$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:
-echo $this->db->count_all('my_table');
-
-// Produces an integer, like 25
-
-
-
-
$this->db->platform()
-
Outputs the database platform you are running (MySQL, MS SQL, Postgres, etc...):
-echo $this->db->platform();
-
-
-
$this->db->version()
-
Outputs the database version you are running:
-echo $this->db->version();
-
-
-
$this->db->last_query();
-
Returns the last query that was run (the query string, not the result). Example:
The first parameter is the table name, the second is an associative array with the data to be updated, and the third parameter is the "where" clause. The above example produces:
- UPDATE table_name SET name = 'Rick', email = 'rick@example.com', url = 'example.com' WHERE author_id = 1 AND status = 'active'
-
-
Note: Values are automatically escaped, producing safer queries.
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/user_guide/database/index.html b/user_guide/database/index.html
deleted file mode 100644
index c85e9bf4c..000000000
--- a/user_guide/database/index.html
+++ /dev/null
@@ -1,99 +0,0 @@
-
-
-
-
-
-The Database Class : CodeIgniter User Guide
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
CodeIgniter comes with a full-featured and very fast abstracted database class that supports both traditional
-structures and Active Record patterns. The database functions offer clear, simple syntax.
The query() function returns a database result object when "read" type queries are run,
-which you can use to show your results. When "write" type queries are run it simply returns TRUE or FALSE
-depending on success or failure. When retrieving data you will typically assign the query to your own variable, like this:
This is a simplified version of the $this->db->query() function. It ONLY returns TRUE/FALSE on success or failure.
-It DOES NOT return a database result set, nor does it set the query timer, or compile bind data, or store your query for debugging.
-It simply lets you submit a query. Most users will rarely use this function.
-
-
-
Working with Database prefixes manually
-
If you have configured a database prefix and would like to prepend it to a table name for use in a native SQL query for example, then you can use the following:
In many databases it is advisable to protect table and field names - for example with backticks in MySQL. Active Record queries are automatically protected, however if you need to manually protect an identifier you can use:
-
$this->db->protect_identifiers('table_name');
-
-
This function will also add a table prefix to your table, assuming you have a prefix specified in your database config file. To enable the prefixing set TRUE (boolen) via the second parameter:
It's a very good security practice to escape your data before submitting it into your database.
-CodeIgniter has three methods that help you do this:
-
-
-
$this->db->escape() This function determines the data type so that it
-can escape only string data. It also automatically adds single quotes around the data so you don't have to:
-
-$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
-
-
$this->db->escape_str() This function escapes the data passed to it, regardless of type.
-Most of the time you'll use the above function rather than this one. Use the function like this:
-
-$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
-
-
$this->db->escape_like_str() This method should be used when strings are to be used in LIKE
-conditions so that LIKE wildcards ('%', '_') in the string are also properly escaped.
-
-$search = '20% raise';
-$sql = "SELECT id FROM table WHERE column LIKE '%".$this->db->escape_like_str($search)."%'";
-
-
-
-
-
Query Bindings
-
-
-
Bindings enable you to simplify your query syntax by letting the system put the queries together for you. Consider the following example:
-
-
-$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
-
The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.
-
The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.
This function returns the query result as an array of objects, or an empty array on failure.
-
- Typically you'll use this in a foreach loop, like this:
You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)
-
-
- $query = $this->db->query("SELECT * FROM users;");
-
- foreach ($query->result('User') as $user)
- {
- echo $user->name; // call attributes
- echo $user->reverse_name(); // or methods defined on the 'User' class
- }
-
-
-
result_array()
-
-
This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:
This function returns a single result row. If your query has more than one row, it returns only the first row.
- The result is returned as an object. Here's a usage example:
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
-
-$query = $this->db->query('SELECT * FROM my_table');
-echo $query->num_rows();
-
-
-
$query->num_fields()
-
The number of FIELDS (columns) returned by the query. Make sure to call the function using your query result object:
-
-$query = $this->db->query('SELECT * FROM my_table');
-echo $query->num_fields();
-
-
-
-
-
$query->free_result()
-
It frees the memory associated with the result and deletes the result resource ID. Normally PHP frees its memory automatically at the end of script
-execution. However, if you are running a lot of queries in a particular script you might want to free the result after each query result has been
-generated in order to cut down on memory consumptions. Example:
-
-
-$query = $this->db->query('SELECT title FROM my_table');
-foreach ($query->result() as $row)
-{
- echo $row->title;
-}
-$query->free_result(); // The $query result object will no longer be available
-
-$query2 = $this->db->query('SELECT name FROM some_table');
-$row = $query2->row();
-echo $row->name;
-$query2->free_result(); // The $query2 result object will no longer be available
-
-
-
-
-
-
-
CodeIgniter's database abstraction allows you to use transactions with databases that support transaction-safe table types. In MySQL, you'll need
-to be running InnoDB or BDB table types rather than the more common MyISAM. Most other database platforms support transactions natively.
-
-
If you are not familiar with
-transactions we recommend you find a good online resource to learn about them for your particular database. The information below assumes you
-have a basic understanding of transactions.
-
-
-
CodeIgniter's Approach to Transactions
-
-
CodeIgniter utilizes an approach to transactions that is very similar to the process used by the popular database class ADODB. We've chosen that approach
-because it greatly simplifies the process of running transactions. In most cases all that is required are two lines of code.
-
-
Traditionally, transactions have required a fair amount of work to implement since they demand that you to keep track of your queries
-and determine whether to commit or rollback based on the success or failure of your queries. This is particularly cumbersome with
-nested queries. In contrast,
-we've implemented a smart transaction system that does all this for you automatically (you can also manage your transactions manually if you choose to,
-but there's really no benefit).
-
-
Running Transactions
-
-
To run your queries using transactions you will use the $this->db->trans_start() and $this->db->trans_complete() functions as follows:
You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure
-of any given query.
-
-
-
Strict Mode
-
-
By default CodeIgniter runs all transactions in Strict Mode. When strict mode is enabled, if you are running multiple groups of
-transactions, if one group fails all groups will be rolled back. If strict mode is disabled, each group is treated independently, meaning
-a failure of one group will not affect any others.
-
-
Strict Mode can be disabled as follows:
-
-$this->db->trans_strict(FALSE);
-
-
-
Managing Errors
-
-
If you have error reporting enabled in your config/database.php file you'll see a standard error message if the commit was unsuccessful. If debugging is turned off, you can
-manage your own errors like this:
-
-
-$this->db->trans_start();
-$this->db->query('AN SQL QUERY...');
-$this->db->query('ANOTHER QUERY...');
-$this->db->trans_complete();
-
-if ($this->db->trans_status() === FALSE)
-{
- // generate an error... or use the log_message() function to log your error
-}
-
-
-
-
Enabling Transactions
-
-
Transactions are enabled automatically the moment you use $this->db->trans_start(). If you would like to disable transactions you
-can do so using $this->db->trans_off():
When transactions are disabled, your queries will be auto-commited, just as they are when running queries without transactions.
-
-
-
Test Mode
-
-
You can optionally put the transaction system into "test mode", which will cause your queries to be rolled back -- even if the queries produce a valid result.
-To use test mode simply set the first parameter in the $this->db->trans_start() function to TRUE:
-
-
-$this->db->trans_start(TRUE); // Query will be rolled back
-$this->db->query('AN SQL QUERY...');
-$this->db->trans_complete();
-
-
-
-
Running Transactions Manually
-
-
If you would like to run transactions manually you can do so as follows:
The second, third, and fourth parameters allow you to
-set the delimiter, newline, and enclosure characters respectively. By default tabs are used as the delimiter, "\n" is used as a new line, and a double-quote is used as the enclosure. Example:
Important: This function will NOT write the CSV file for you. It simply creates the CSV layout.
-If you need to write the file use the File Helper.
-
-
-
$this->dbutil->xml_from_result($db_result)
-
-
Permits you to generate an XML file from a query result. The first parameter expects a query result object, the second
-may contain an optional array of config parameters. Example:
Important: This function will NOT write the XML file for you. It simply creates the XML layout.
-If you need to write the file use the File Helper.
-
-
-
$this->dbutil->backup()
-
-
Permits you to backup your full database or individual tables. The backup data can be compressed in either Zip or Gzip format.
-
-
Note: This features is only available for MySQL databases.
-
-
Note: Due to the limited execution time and memory available to PHP, backing up very large
-databases may not be possible. If your database is very large you might need to backup directly from your SQL server
-via the command line, or have your server admin do it for you if you do not have root privileges.
-
-
Usage Example
-
-
-// Load the DB utility class
-$this->load->dbutil();
-
-// Backup your entire database and assign it to a variable
-$backup =& $this->dbutil->backup();
-
-
-// Load the file helper and write the file to your server
-$this->load->helper('file');
-write_file('/path/to/mybackup.gz', $backup);
-
-
-// Load the download helper and send the file to your desktop
-$this->load->helper('download');
-force_download('mybackup.gz', $backup);
-
-
-
Setting Backup Preferences
-
-
Backup preferences are set by submitting an array of values to the first parameter of the backup function. Example:
-
-$prefs = array(
- 'tables' => array('table1', 'table2'), // Array of tables to backup.
- 'ignore' => array(), // List of tables to omit from the backup
- 'format' => 'txt', // gzip, zip, txt
- 'filename' => 'mybackup.sql', // File name - NEEDED ONLY WITH ZIP FILES
- 'add_drop' => TRUE, // Whether to add DROP TABLE statements to backup file
- 'add_insert' => TRUE, // Whether to add INSERT data to backup file
- 'newline' => "\n" // Newline character used in backup file
- );
-
-$this->dbutil->backup($prefs);
-
-
-
-
Description of Backup Preferences
-
-
-
-
Preference
-
Default Value
-
Options
-
Description
-
-
tables
empty array
None
An array of tables you want backed up. If left blank all tables will be exported.
-
-
ignore
empty array
None
An array of tables you want the backup routine to ignore.
-
-
format
gzip
gzip, zip, txt
The file format of the export file.
-
-
filename
the current date/time
None
The name of the backed-up file. The name is needed only if you are using zip compression.
-
-
add_drop
TRUE
TRUE/FALSE
Whether to include DROP TABLE statements in your SQL export file.
-
-
add_insert
TRUE
TRUE/FALSE
Whether to include INSERT statements in your SQL export file.
-
-
newline
"\n"
"\n", "\r", "\r\n"
Type of newline to use in your SQL export file.
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
--
cgit v1.2.3-24-g4f1b