summaryrefslogtreecommitdiffstats
path: root/user_guide_src/source/database
diff options
context:
space:
mode:
Diffstat (limited to 'user_guide_src/source/database')
-rw-r--r--user_guide_src/source/database/configuration.rst147
-rw-r--r--user_guide_src/source/database/connecting.rst36
-rw-r--r--user_guide_src/source/database/examples.rst8
-rw-r--r--user_guide_src/source/database/forge.rst61
-rw-r--r--user_guide_src/source/database/index.rst4
-rw-r--r--user_guide_src/source/database/queries.rst32
-rw-r--r--user_guide_src/source/database/query_builder.rst (renamed from user_guide_src/source/database/active_record.rst)160
-rw-r--r--user_guide_src/source/database/results.rst53
-rw-r--r--user_guide_src/source/database/utilities.rst78
9 files changed, 376 insertions, 203 deletions
diff --git a/user_guide_src/source/database/configuration.rst b/user_guide_src/source/database/configuration.rst
index 3f3bae336..34cefffbd 100644
--- a/user_guide_src/source/database/configuration.rst
+++ b/user_guide_src/source/database/configuration.rst
@@ -12,26 +12,46 @@ it the respective environment config folder.
The config settings are stored in a multi-dimensional array with this
prototype::
- $db['default']['hostname'] = "localhost";
- $db['default']['username'] = "root";
- $db['default']['password'] = "";
- $db['default']['database'] = "database_name";
- $db['default']['dbdriver'] = "mysql";
- $db['default']['dbprefix'] = "";
- $db['default']['pconnect'] = TRUE;
- $db['default']['db_debug'] = FALSE;
- $db['default']['cache_on'] = FALSE;
- $db['default']['cachedir'] = "";
- $db['default']['char_set'] = "utf8";
- $db['default']['dbcollat'] = "utf8_general_ci";
- $db['default']['swap_pre'] = "";
- $db['default']['autoinit'] = TRUE;
- $db['default']['stricton'] = FALSE;
-
-If you use PDO as your dbdriver, you can specify the full DSN string describe a connection to the database like this::
-
+ $db['default'] = array(
+ 'dsn' => '',
+ 'hostname' => 'localhost',
+ 'username' => 'root',
+ 'password' => '',
+ 'database' => 'database_name',
+ 'dbdriver' => 'mysqli',
+ 'dbprefix' => '',
+ 'pconnect' => TRUE,
+ 'db_debug' => TRUE,
+ 'cache_on' => FALSE,
+ 'cachedir' => '',
+ 'char_set' => 'utf8',
+ 'dbcollat' => 'utf8_general_ci',
+ 'swap_pre' => '',
+ 'autoinit' => TRUE,
+ 'encrypt' => FALSE,
+ 'compress' => FALSE,
+ 'stricton' => FALSE,
+ 'failover' => array()
+ );
+
+Some database drivers (such as PDO, PostgreSQL, Oracle, ODBC) might
+require a full DSN string to be provided. If that is the case, you
+should use the 'dsn' configuration setting, as if you're using the
+driver's underlying native PHP extension, like this::
+
+ // PDO
$db['default']['dsn'] = 'pgsql:host=localhost;port=5432;dbname=database_name';
+ // Oracle
+ $db['default']['dsn'] = '//localhost/XE';
+
+.. note:: If you do not specify a DSN string for a driver that requires it, CodeIgniter
+ will try to build it with the rest of the provided settings.
+
+.. note:: If you provide a DSN string and it is missing some valid settings (e.g. the
+ database character set), which are present in the rest of the configuration
+ fields, CodeIgniter will append them.
+
You can also specify failovers for the situation when the main connection cannot connect for some reason.
These failovers can be specified by setting the failover for a connection like this::
@@ -41,7 +61,7 @@ These failovers can be specified by setting the failover for a connection like t
'username' => '',
'password' => '',
'database' => '',
- 'dbdriver' => 'mysql',
+ 'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
@@ -51,6 +71,8 @@ These failovers can be specified by setting the failover for a connection like t
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'encrypt' => FALSE,
+ 'compress' => FALSE,
'stricton' => FALSE
),
array(
@@ -58,7 +80,7 @@ These failovers can be specified by setting the failover for a connection like t
'username' => '',
'password' => '',
'database' => '',
- 'dbdriver' => 'mysql',
+ 'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
@@ -68,6 +90,8 @@ These failovers can be specified by setting the failover for a connection like t
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
+ 'encrypt' => FALSE,
+ 'compress' => FALSE,
'stricton' => FALSE
)
);
@@ -81,46 +105,52 @@ 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::
- $db['test']['hostname'] = "localhost";
- $db['test']['username'] = "root";
- $db['test']['password'] = "";
- $db['test']['database'] = "database_name";
- $db['test']['dbdriver'] = "mysql";
- $db['test']['dbprefix'] = "";
- $db['test']['pconnect'] = TRUE;
- $db['test']['db_debug'] = FALSE;
- $db['test']['cache_on'] = FALSE;
- $db['test']['cachedir'] = "";
- $db['test']['char_set'] = "utf8";
- $db['test']['dbcollat'] = "utf8_general_ci";
- $db['test']['swap_pre'] = "";
- $db['test']['autoinit'] = TRUE;
- $db['test']['stricton'] = FALSE;
+ $db['test'] = array(
+ 'dsn' => '',
+ 'hostname' => 'localhost',
+ 'username' => 'root',
+ 'password' => '',
+ 'database' => 'database_name',
+ 'dbdriver' => 'mysqli',
+ 'dbprefix' => '',
+ 'pconnect' => TRUE,
+ 'db_debug' => TRUE,
+ 'cache_on' => FALSE,
+ 'cachedir' => '',
+ 'char_set' => 'utf8',
+ 'dbcollat' => 'utf8_general_ci',
+ 'swap_pre' => '',
+ 'autoinit' => TRUE,
+ 'compress' => FALSE,
+ 'encrypt' => FALSE,
+ 'stricton' => FALSE,
+ 'failover' => array()
+ );
Then, to globally tell the system to use that group you would set this
variable located in the config file::
- $active_group = "test";
+ $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.
+.. 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
+Query Builder
-------------
-The :doc:`Active Record Class <active_record>` is globally enabled or
-disabled by setting the $active_record variable in the database
+The :doc:`Query Builder Class <query_builder>` is globally enabled or
+disabled by setting the $query_builder 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
+query builder class, setting it to FALSE will utilize fewer resources
when the database classes are initialized.
::
- $active_record = TRUE;
+ $query_builder = TRUE;
-.. note:: that some CodeIgniter classes such as Sessions require Active
- Records be enabled to access certain functionality.
+.. note:: that some CodeIgniter classes such as Sessions require Query
+ Builder to be enabled to access certain functionality.
Explanation of Values:
----------------------
@@ -128,13 +158,14 @@ Explanation of Values:
====================== ==================================================================================================
Name Config Description
====================== ==================================================================================================
-**hostname** The hostname of your database server. Often this is "localhost".
+**dsn** The DSN connect string (an all-in-one configuration sequence).
+**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, postgre, odbc, etc. Must be specified in lower case.
+**dbdriver** The database type. ie: mysqli, postgre, odbc, etc. Must be specified in lower case.
**dbprefix** An optional table prefix which will added to the table name when running :doc:
- `Active Record <active_record>` queries. This permits multiple CodeIgniter installations
+ `Query Builder <query_builder>` 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.
@@ -144,30 +175,26 @@ Explanation of Values:
**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.
+ .. note:: Only used in the 'mysql' and 'mysqli' drivers.
**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.
+**schema** The database schema, defaults to 'public'. Used by PostgreSQL and ODBC drivers.
+**encrypt** Whether or not to use an encrypted connection.
+**compress** Whether or not to use client compression (MySQL only).
**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;
+
+ $db['default']['port'] = 5432;
====================== ==================================================================================================
.. note:: Depending on what database platform you are using (MySQL, PostgreSQL,
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.
+ you are using MySQL. \ No newline at end of file
diff --git a/user_guide_src/source/database/connecting.rst b/user_guide_src/source/database/connecting.rst
index fb4524116..9b8117076 100644
--- a/user_guide_src/source/database/connecting.rst
+++ b/user_guide_src/source/database/connecting.rst
@@ -36,7 +36,7 @@ Available Parameters
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
+#. TRUE/FALSE (boolean). Whether to enable the Query Builder class. Set
to TRUE by default.
Manually Connecting to a Database
@@ -57,25 +57,28 @@ file.
To connect manually to a desired database you can pass an array of
values::
- $config['hostname'] = "localhost";
- $config['username'] = "myusername";
- $config['password'] = "mypassword";
- $config['database'] = "mydatabase";
- $config['dbdriver'] = "mysql";
- $config['dbprefix'] = "";
- $config['pconnect'] = FALSE;
- $config['db_debug'] = TRUE;
- $config['cache_on'] = FALSE;
- $config['cachedir'] = "";
- $config['char_set'] = "utf8";
- $config['dbcollat'] = "utf8_general_ci";
+ $config['hostname'] = 'localhost';
+ $config['username'] = 'myusername';
+ $config['password'] = 'mypassword';
+ $config['database'] = 'mydatabase';
+ $config['dbdriver'] = 'mysqli';
+ $config['dbprefix'] = '';
+ $config['pconnect'] = FALSE;
+ $config['db_debug'] = TRUE;
+ $config['cache_on'] = FALSE;
+ $config['cachedir'] = '';
+ $config['char_set'] = 'utf8';
+ $config['dbcollat'] = 'utf8_general_ci';
$this->load->database($config);
For information on each of these values please see the :doc:`configuration
page <configuration>`.
-.. note:: For the PDO driver, $config['hostname'] should look like
- this: 'mysql:host=localhost'
+.. note:: For the PDO driver, you should use the $config['dsn'] setting
+ instead of 'hostname' and 'database':
+
+ |
+ | $config['dsn'] = 'mysql:host=localhost;dbname=mydatabase';
Or you can submit your database values as a Data Source Name. DSNs must
have this prototype::
@@ -149,5 +152,4 @@ connections, you can explicitly close the connection.
::
- $this->db->close();
-
+ $this->db->close(); \ No newline at end of file
diff --git a/user_guide_src/source/database/examples.rst b/user_guide_src/source/database/examples.rst
index d1cd48837..8b3cc4701 100644
--- a/user_guide_src/source/database/examples.rst
+++ b/user_guide_src/source/database/examples.rst
@@ -104,10 +104,10 @@ Standard Insert
$this->db->query($sql);
echo $this->db->affected_rows();
-Active Record Query
+Query Builder Query
===================
-The :doc:`Active Record Pattern <active_record>` gives you a simplified
+The :doc:`Query Builder Pattern <query_builder>` gives you a simplified
means of retrieving data::
$query = $this->db->get('table_name');
@@ -118,10 +118,10 @@ means of retrieving data::
}
The above get() function retrieves all the results from the supplied
-table. The :doc:`Active Record <active_record>` class contains a full
+table. The :doc:`Query Builder <query_builder>` class contains a full
compliment of functions for working with data.
-Active Record Insert
+Query Builder Insert
====================
::
diff --git a/user_guide_src/source/database/forge.rst b/user_guide_src/source/database/forge.rst
index bf17e2918..ca904ed00 100644
--- a/user_guide_src/source/database/forge.rst
+++ b/user_guide_src/source/database/forge.rst
@@ -2,7 +2,7 @@
Database Forge Class
####################
-The Database Forge Class contains functions that help you manage your
+The Database Forge Class contains methods that help you manage your
database.
.. contents:: Table of Contents
@@ -18,13 +18,25 @@ Load the Forge Class as follows::
$this->load->dbforge()
-Once initialized you will access the functions using the $this->dbforge
+You can also pass another database object to the DB Forge loader, in case
+the database you want to manage isn't the default one::
+
+ $this->myforge = $this->load->dbforge($this->other_db, TRUE);
+
+In the above example, we're passing a custom database object as the first
+parameter and then tell it to return the dbforge object, instead of
+assigning it directly to ``$this->dbforge``.
+
+.. note:: Both of the parameters can be used individually, just pass an empty
+ value as the first one if you wish to skip it.
+
+Once initialized you will access the methods using the ``$this->dbforge``
object::
- $this->dbforge->some_function()
+ $this->dbforge->some_method();
$this->dbforge->create_database('db_name')
-============================================
+==========================================
Permits you to create the database specified in the first parameter.
Returns TRUE/FALSE based on success or failure::
@@ -108,13 +120,13 @@ Additionally, the following key/values can be used:
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($fields);`` followed by a call to the
+``create_table()`` method.
$this->dbforge->add_field()
-----------------------------
+---------------------------
-The add fields function will accept the above array.
+The add fields method will accept the above array.
Passing strings as fields
-------------------------
@@ -193,13 +205,15 @@ into the definition
Dropping a table
================
-Executes a DROP TABLE sql
+Execute a DROP TABLE statement and optionally add an IF EXISTS clause.
::
+ // Produces: DROP TABLE table_name
$this->dbforge->drop_table('table_name');
- // gives DROP TABLE IF EXISTS table_name
+ // Produces: DROP TABLE IF EXISTS table_name
+ $this->dbforge->drop_table('table_name');
Renaming a table
================
@@ -217,9 +231,9 @@ Modifying Tables
****************
$this->dbforge->add_column()
-=============================
+============================
-The add_column() function is used to modify an existing table. It
+The ``add_column()`` method 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.
@@ -229,18 +243,25 @@ number of additional fields.
'preferences' => array('type' => 'TEXT')
);
$this->dbforge->add_column('table_name', $fields);
- // gives ALTER TABLE table_name ADD preferences TEXT
+ // Executes: ALTER TABLE table_name ADD preferences TEXT
-An optional third parameter can be used to specify which existing column
-to add the new column after.
+If you are using MySQL or CUBIRD, then you can take advantage of their
+AFTER and FIRST clauses to position the new column.
-::
+Examples::
- $this->dbforge->add_column('table_name', $fields, 'after_field');
+ // Will place the new column after the `another_field` column:
+ $fields = array(
+ 'preferences' => array('type' => 'TEXT', 'after' => 'another_field')
+ );
+ // Will place the new column at the start of the table definition:
+ $fields = array(
+ 'preferences' => array('type' => 'TEXT', 'first' => TRUE)
+ );
$this->dbforge->drop_column()
-==============================
+=============================
Used to remove a column from a table.
@@ -250,9 +271,9 @@ Used to remove a column from a table.
$this->dbforge->modify_column()
-================================
+===============================
-The usage of this function is identical to add_column(), except it
+The usage of this method 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.
diff --git a/user_guide_src/source/database/index.rst b/user_guide_src/source/database/index.rst
index ab12b7cb7..7ccb8fb00 100644
--- a/user_guide_src/source/database/index.rst
+++ b/user_guide_src/source/database/index.rst
@@ -3,7 +3,7 @@ The Database Class
##################
CodeIgniter comes with a full-featured and very fast abstracted database
-class that supports both traditional structures and Active Record
+class that supports both traditional structures and Query Builder
patterns. The database functions offer clear, simple syntax.
.. toctree::
@@ -15,7 +15,7 @@ patterns. The database functions offer clear, simple syntax.
Running Queries <queries>
Generating Query Results <results>
Query Helper Functions <helpers>
- Active Record Class <active_record>
+ Query Builder Class <query_builder>
Transactions <transactions>
Table MetaData <table_data>
Field MetaData <fields>
diff --git a/user_guide_src/source/database/queries.rst b/user_guide_src/source/database/queries.rst
index 15a73614a..11dd78392 100644
--- a/user_guide_src/source/database/queries.rst
+++ b/user_guide_src/source/database/queries.rst
@@ -21,11 +21,31 @@ this::
$this->db->simple_query();
===========================
-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.
+This is a simplified version of the $this->db->query() method. 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.
+
+It returns whatever the database drivers' "execute" function returns.
+That typically is TRUE/FALSE on success or failure for write type queries
+such as INSERT, DELETE or UPDATE statements (which is what it really
+should be used for) and a resource/object on success for queries with
+fetchable results.
+
+::
+
+ if ($this->db->simple_query('YOUR QUERY'))
+ {
+ echo "Success!";
+ }
+ else
+ {
+ echo "Query failed!";
+ }
+
+.. note:: PostgreSQL's pg_exec() function always returns a resource on
+ success, even for write type queries. So take that in mind if
+ you're looking for a boolean value.
***************************************
Working with Database prefixes manually
@@ -50,7 +70,7 @@ Protecting identifiers
**********************
In many databases it is advisable to protect table and field names - for
-example with backticks in MySQL. **Active Record queries are
+example with backticks in MySQL. **Query Builder queries are
automatically protected**, however if you need to manually protect an
identifier you can use::
diff --git a/user_guide_src/source/database/active_record.rst b/user_guide_src/source/database/query_builder.rst
index e328c11e2..65609c1cb 100644
--- a/user_guide_src/source/database/active_record.rst
+++ b/user_guide_src/source/database/query_builder.rst
@@ -1,15 +1,15 @@
###################
-Active Record Class
+Query Builder Class
###################
-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 gives you access to a Query Builder class. 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
+Beyond simplicity, a major benefit to using the Query Builder 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
@@ -67,8 +67,8 @@ Example::
// Produces string: SELECT * FROM mytable
-The second parameter enables you to set whether or not the active record query
-will be reset (by default it will be just like `$this->db->get()`)::
+The second parameter enables you to set whether or not the query builder query
+will be reset (by default it will be&mdash;just like `$this->db->get()`)::
echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);
// Produces string: SELECT * FROM mytable LIMIT 20, 10
@@ -345,23 +345,24 @@ if appropriate
$this->db->like()
=================
-This function enables you to generate **LIKE** clauses, useful for doing
+This method enables you to generate **LIKE** clauses, useful for doing
searches.
-.. note:: All values passed to this function are escaped automatically.
+.. note:: All values passed to this method are escaped automatically.
#. **Simple key/value method:**
::
- $this->db->like('title', 'match'); // Produces: WHERE title LIKE '%match%'
+ $this->db->like('title', 'match');
+ // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
- If you use multiple function calls they will be chained together with
+ If you use multiple method calls they will be chained together with
AND between them::
$this->db->like('title', 'match');
$this->db->like('body', 'match');
- // WHERE title LIKE '%match%' AND body LIKE '%match%
+ // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
If you want to control where the wildcard (%) is placed, you can use
an optional third argument. Your options are 'before', 'after' and
@@ -369,9 +370,9 @@ searches.
::
- $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%'
+ $this->db->like('title', 'match', 'before'); // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
+ $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
+ $this->db->like('title', 'match', 'both'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
#. **Associative array method:**
@@ -379,37 +380,37 @@ searches.
$array = array('title' => $match, 'page1' => $match, 'page2' => $match);
$this->db->like($array);
- // WHERE title LIKE '%match%' AND page1 LIKE '%match%' AND page2 LIKE '%match%'
+ // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
$this->db->or_like()
====================
-This function is identical to the one above, except that multiple
+This method is identical to the one above, except that multiple
instances are joined by OR::
$this->db->like('title', 'match'); $this->db->or_like('body', $match);
- // WHERE title LIKE '%match%' OR body LIKE '%match%'
+ // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
-.. note:: or_like() was formerly known as orlike(), which has been removed.
+.. note:: ``or_like()`` was formerly known as ``orlike()``, which has been removed.
$this->db->not_like()
=====================
-This function is identical to **like()**, except that it generates NOT
-LIKE statements::
+This method is identical to ``like()``, except that it generates
+NOT LIKE statements::
- $this->db->not_like('title', 'match'); // WHERE title NOT LIKE '%match%
+ $this->db->not_like('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
$this->db->or_not_like()
========================
-This function is identical to **not_like()**, except that multiple
+This method is identical to ``not_like()``, except that multiple
instances are joined by OR::
$this->db->like('title', 'match');
$this->db->or_not_like('body', 'match');
- // WHERE title LIKE '%match% OR body NOT LIKE '%match%'
+ // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
$this->db->group_by()
=====================
@@ -469,31 +470,47 @@ 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.
+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**.
::
- $this->db->order_by("title", "desc"); // Produces: ORDER BY title DESC
+ $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
+ $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
+ $this->db->order_by('title', 'DESC');
+ $this->db->order_by('name', 'ASC');
+ // Produces: ORDER BY `title` DESC, `name` ASC
+
+If you choose the **RANDOM** direction option, then the first parameters will
+be ignored, unless you specify a numeric seed value.
+
+::
+
+ $this->db->order_by('title', 'RANDOM');
+ // Produces: ORDER BY RAND()
+ $this->db->order_by(42, 'RANDOM');
+ // Produces: ORDER BY RAND(42)
.. 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'.
+.. note:: Random ordering is not currently supported in Oracle and
+ will default to ASC instead.
$this->db->limit()
==================
@@ -512,7 +529,7 @@ $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
+Record query. Queries will accept Query Builder restrictors such as
where(), or_where(), like(), or_like(), etc. Example::
echo $this->db->count_all_results('my_table'); // Produces an integer, like 25
@@ -603,9 +620,9 @@ Here is an example using an object::
/*
class Myclass {
- var $title = 'My Title';
- var $content = 'My Content';
- var $date = 'My Date';
+ public $title = 'My Title';
+ public $content = 'My Content';
+ public $date = 'My Date';
}
*/
@@ -636,7 +653,7 @@ Example::
// Produces string: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
-The second parameter enables you to set whether or not the active record query
+The second parameter enables you to set whether or not the query builder query
will be reset (by default it will be--just like `$this->db->insert()`_)::
echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);
@@ -681,6 +698,35 @@ associative 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 SQL
+standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE*
+keys as the determining factor.
+In our case, it will save you from the need to implement complex
+logics with different combinations of ``select()``, ``update()``,
+``delete()`` and ``insert()`` calls.
+
+Example::
+
+ $data = array(
+ 'title' => 'My title',
+ 'name' => 'My Name',
+ 'date' => 'My date'
+ );
+
+ $this->db->replace('table', $data);
+
+ // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
+
+In the above example, if we assume that the *title* field is our primary
+key, then if a row containing 'My title' as the *title* value, that row
+will be deleted with our new row data replacing it.
+
+Usage of the ``set()`` method is also allowed and all fields are
+automatically escaped, just like with ``insert()``.
+
$this->db->set()
================
@@ -730,9 +776,9 @@ Or an object::
/*
class Myclass {
- var $title = 'My Title';
- var $content = 'My Content';
- var $date = 'My Date';
+ public $title = 'My Title';
+ public $content = 'My Content';
+ public $date = 'My Date';
}
*/
@@ -740,7 +786,6 @@ Or an object::
$this->db->set($object);
$this->db->insert('mytable');
-
*************
Updating Data
*************
@@ -766,9 +811,9 @@ Or you can supply an object::
/*
class Myclass {
- var $title = 'My Title';
- var $content = 'My Content';
- var $date = 'My Date';
+ public $title = 'My Title';
+ public $content = 'My Content';
+ public $date = 'My Date';
}
*/
@@ -792,6 +837,7 @@ Or as an array::
You may also use the $this->db->set() function described above when
performing updates.
+
$this->db->update_batch()
=========================
@@ -830,6 +876,10 @@ array 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()
================================
@@ -928,12 +978,12 @@ multiple functions. Consider this example::
.. _ar-caching:
*********************
-Active Record Caching
+Query Builder Caching
*********************
-While not "true" caching, Active Record enables you to save (or "cache")
+While not "true" caching, Query Builder 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,
+script's execution. Normally, when an Query Builder call is completed,
all stored information is reset for the next call. With caching, you can
prevent this reset, and reuse information easily.
@@ -944,7 +994,7 @@ There are three Caching functions available:
$this->db->start_cache()
========================
-This function must be called to begin caching. All Active Record queries
+This function must be called to begin caching. All Query Builder queries
of the correct type (see below for supported queries) are stored for
later use.
@@ -956,7 +1006,7 @@ This function can be called to stop caching.
$this->db->flush_cache()
========================
-This function deletes all items from the Active Record cache.
+This function deletes all items from the Query Builder cache.
Here's a usage example::
@@ -983,12 +1033,12 @@ Here's a usage example::
$this->db->reset_query()
========================
-Resetting Active Record allows you to start fresh with your query without
+Resetting Query Builder allows you to start fresh with your query without
executing 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've
-cached using `Active Record Caching`_.
+cached using `Query Builder Caching`_.
-This is useful in situations where you are using Active Record to generate SQL
+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::
@@ -1005,4 +1055,4 @@ run the query::
$data = $this->db->get()->result_array();
// Would execute and return an array of results of the following query:
- // SELECT field1, field1 from mytable where field3 = 5;
+ // SELECT field1, field1 from mytable where field3 = 5; \ No newline at end of file
diff --git a/user_guide_src/source/database/results.rst b/user_guide_src/source/database/results.rst
index 865345762..e0a87a851 100644
--- a/user_guide_src/source/database/results.rst
+++ b/user_guide_src/source/database/results.rst
@@ -99,7 +99,7 @@ to instantiate the row with::
echo $row->reverse_name(); // or methods defined on the 'User' class
row_array()
-============
+===========
Identical to the above row() function, except it returns an array.
Example::
@@ -136,12 +136,39 @@ parameter:
| **$row = $query->next_row('array')**
| **$row = $query->previous_row('array')**
+.. note:: all the functions above will load the whole result into memory (prefetching) use unbuffered_row() for processing large result sets.
+
+unbuffered_row()
+================
+
+This method returns a single result row without prefetching the whole
+result in memory as ``row()`` does. If your query has more than one row,
+it returns the current row and moves the internal data pointer ahead.
+
+::
+
+ $query = $this->db->query("YOUR QUERY");
+
+ while ($row = $query->unbuffered_row())
+ {
+ echo $row->title;
+ echo $row->name;
+ echo $row->body;
+ }
+
+You can optionally pass 'object' (default) or 'array' in order to specify
+the returned value's type::
+
+ $query->unbuffered_row(); // object
+ $query->unbuffered_row('object'); // object
+ $query->unbuffered_row('array'); // associative array
+
***********************
Result Helper Functions
***********************
$query->num_rows()
-===================
+==================
The number of rows returned by the query. Note: In this example, $query
is the variable that the query result object is assigned to::
@@ -157,7 +184,7 @@ is the variable that the query result object is assigned to::
resulting array in order to achieve the same functionality.
$query->num_fields()
-=====================
+====================
The number of FIELDS (columns) returned by the query. Make sure to call
the function using your query result object::
@@ -167,7 +194,7 @@ the function using your query result object::
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
@@ -189,3 +216,21 @@ Example::
$row = $query2->row();
echo $row->name;
$query2->free_result(); // The $query2 result object will no longer be available
+
+data_seek()
+===========
+
+This method sets the internal pointer for the next result row to be
+fetched. It is only useful in combination with ``unbuffered_row()``.
+
+It accepts a positive integer value, which defaults to 0 and returns
+TRUE on success or FALSE on failure.
+
+::
+
+ $query = $this->db->query('SELECT `field_name` FROM `table_name`');
+ $query->data_seek(5); // Skip the first 5 rows
+ $row = $query->unbuffered_row();
+
+.. note:: Not all database drivers support this feature and will return FALSE.
+ Most notably - you won't be able to use it with PDO. \ No newline at end of file
diff --git a/user_guide_src/source/database/utilities.rst b/user_guide_src/source/database/utilities.rst
index 4e83929b2..06ecb2da1 100644
--- a/user_guide_src/source/database/utilities.rst
+++ b/user_guide_src/source/database/utilities.rst
@@ -2,7 +2,7 @@
Database Utility Class
######################
-The Database Utility Class contains functions that help you manage your
+The Database Utility Class contains methods that help you manage your
database.
.. contents:: Table of Contents
@@ -22,12 +22,24 @@ Load the Utility Class as follows::
$this->load->dbutil()
-Once initialized you will access the functions using the $this->dbutil
+You can also pass another database object to the DB Utility loader, in case
+the database you want to manage isn't the default one::
+
+ $this->myutil = $this->load->dbutil($this->other_db, TRUE);
+
+In the above example, we're passing a custom database object as the first
+parameter and then tell it to return the dbutil object, instead of
+assigning it directly to ``$this->dbutil``.
+
+.. note:: Both of the parameters can be used individually, just pass an empty
+ value as the first one if you wish to skip it.
+
+Once initialized you will access the methods using the ``$this->dbutil``
object::
- $this->dbutil->some_function()
+ $this->dbutil->some_method()
-$this->dbutil->list_databases()
+$this->dbutil->list_databases();
================================
Returns an array of database names::
@@ -40,7 +52,7 @@ Returns an array of database names::
}
$this->dbutil->database_exists();
-==================================
+=================================
Sometimes it's helpful to know whether a particular database exists.
Returns a boolean TRUE/FALSE. Usage example::
@@ -50,13 +62,11 @@ Returns a boolean TRUE/FALSE. Usage example::
// some code...
}
-Note: Replace *database_name* with the name of the table you are
-looking for. This function is case sensitive.
+.. note:: Replace *database_name* with the name of the table you are
+ looking for. This method is case sensitive.
$this->dbutil->optimize_table('table_name');
-==============================================
-
-.. note:: This features is only available for MySQL/MySQLi databases.
+============================================
Permits you to optimize a table using the table name specified in the
first parameter. Returns TRUE/FALSE based on success or failure::
@@ -66,12 +76,11 @@ first parameter. Returns TRUE/FALSE based on success or failure::
echo 'Success!';
}
-.. note:: Not all database platforms support table optimization.
+.. note:: Not all database platforms support table optimization. It is
+ mostly for use with MySQL.
$this->dbutil->repair_table('table_name');
-============================================
-
-.. note:: This features is only available for MySQL/MySQLi databases.
+==========================================
Permits you to repair a table using the table name specified in the
first parameter. Returns TRUE/FALSE based on success or failure::
@@ -86,8 +95,6 @@ first parameter. Returns TRUE/FALSE based on success or failure::
$this->dbutil->optimize_database();
====================================
-.. note:: This features is only available for MySQL/MySQLi databases.
-
Permits you to optimize the database your DB class is currently
connected to. Returns an array containing the DB status messages or
FALSE on failure.
@@ -101,13 +108,14 @@ FALSE on failure.
print_r($result);
}
-.. note:: Not all database platforms support table optimization.
+.. note:: Not all database platforms support table optimization. It
+ it is mostly for use with MySQL.
-$this->dbutil->csv_from_result($db_result)
-=============================================
+$this->dbutil->csv_from_result($db_result);
+===========================================
Permits you to generate a CSV file from a query result. The first
-parameter of the function must contain the result object from your
+parameter of the method must contain the result object from your
query. Example::
$this->load->dbutil();
@@ -127,12 +135,12 @@ is used as the enclosure. Example::
echo $this->dbutil->csv_from_result($query, $delimiter, $newline, $enclosure);
-.. important:: This function will NOT write the CSV file for you. It
+.. important:: This method will NOT write the CSV file for you. It
simply creates the CSV layout. If you need to write the file
use the :doc:`File Helper <../helpers/file_helper>`.
-$this->dbutil->xml_from_result($db_result)
-=============================================
+$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
@@ -151,17 +159,17 @@ optional array of config parameters. Example::
echo $this->dbutil->xml_from_result($query, $config);
-.. important:: This function will NOT write the XML file for you. It
+.. important:: This method will NOT write the XML file for you. It
simply creates the XML layout. If you need to write the file
use the :doc:`File Helper <../helpers/file_helper>`.
-$this->dbutil->backup()
-=======================
+$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 and Interbase/Firebird databases.
+.. note:: This feature is only available for MySQL and Interbase/Firebird databases.
.. note:: For Interbase/Firebird databases, the backup file name is the only parameter.
@@ -196,16 +204,16 @@ Setting Backup Preferences
--------------------------
Backup preferences are set by submitting an array of values to the first
-parameter of the backup function. Example::
+parameter of the ``backup()`` method. 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
+ '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);