Problems with CI connection to multiple databases

Source: Internet
Author: User
Tags pconnect
PS: The CI database has been entangled in connecting to the two databases for a long time. It has been correct according to what I have said on the Internet, but I cannot get through. After reading this article, I suddenly understood that the solution has been highlighted. The following code describes how to use a database. For more information, see the separate function introduction page. Initialize

PS: The CI database has been entangled in connecting to the two databases for a long time. It has been correct according to what I have said on the Internet, but I cannot get through. After reading this article, I suddenly understood that the solution has been highlighted. The following code describes how to use a database. For more information, see the separate function introduction page. Initialize

PS: The CI database has been entangled in connecting to the two databases for a long time. It has been correct according to what I have said on the Internet, but I cannot get through. After reading this article, I suddenly understood that the solution has been highlighted.


Database Quick Start example code
The following describes how to use a database. For more information, see the separate function introduction page.

Initialize Database Class
The following code loads and initializes the Database Class Based on your Database Configuration:

$ This-> load-> database ();

Once loaded, you can use it anywhere like this:

NOTE: If all your pages require database class initialization, you can make it automatically loaded. For more information, see database connection.

Standard multi-result query (object form)
$ Query = $ this-> db-> query ('selectname, title, email FROM my_table ');

Foreach ($ query-> result () as $ row)
{
Echo $ row-> title;
Echo $ row-> name;
Echo $ row-> email;
}

Echo 'total Results: '. $ query-> num_rows ();
The result () function above returns an array of objects. Example: $ row-> title

Standard multi-result query (in array format)
$ Query = $ this-> db-> query ('selectname, title, email FROM my_table ');

Foreach ($ query-> result_array () as $ row)
{
Echo $ row ['title'];
Echo $ row ['name'];
Echo $ row ['email '];
}

The above result_array () function returns an array with the lower mark. Example: $ row ['title']

Test query results
If your query may not return results, we recommend that you use the num_rows () function to test:

$ Query = $ this-> db-> query ("YOURQUERY ");

If ($ query-> num_rows ()> 0)
{
Foreach ($ query-> result () as $ row)
{
Echo $ row-> title;
Echo $ row-> name;
Echo $ row-> body;
}
}
Standard Single-result query (object form)
$ Query = $ this-> db-> query ('selectname FROM my_table LIMIT 1 ');

$ Row = $ query-> row ();
Echo $ row-> name;

The row () function above returns an object. Example: $ row-> name

Standard Single-result query (in array format)
$ Query = $ this-> db-> query ('selectname FROM my_table LIMIT 1 ');

$ Row = $ query-> row_array ();
Echo $ row ['name'];

The row_array () function above returns an array. Example: $ row ['name']

Standard insert)
$ SQL = "INSERT INTO mytable (title, name)
VALUES (". $ this-> db-> escape ($ title).", ". $ this-> db-> escape ($ name ).")";

$ This-> db-> query ($ SQL );

Echo $ this-> db-> affected_rows ();
Quick query
The Quick query class provides us with a way to quickly obtain data:

$ Query = $ this-> db-> get ('table _ name ');

Foreach ($ query-> result () as $ row)
{
Echo $ row-> title;
}

The get () function above returns all results in the data table. The Quick query class provides quick functions for all database operations.

Insert)
$ Data = array (
'Title' => $ title,
'Name' => $ name,
'Date' => $ date
);

$ This-> db-> insert ('mytable', $ data );

// Produces: insert into mytable (title, name, date) VALUES ('{$ title}', '{$ name}', '{$ date }')

Database Configuration
CodeIgniter has a configuration file that stores the database connection values (username: username, password: password, databasename: database name, etc.). The configuration file is located in the following path:

Application/config/database. php

The accessory file is stored in a multi-dimensional array in the following format:

$ Db ['default'] ['hostname'] = "localhost ";
$ Db ['default'] ['username'] = "root ";
$ Db ['default'] ['Password'] = "";
$ Db ['default'] ['databas'] = "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 ";

The reason we use multi-dimensional arrays is to allow you to store multiple connection values at will. For example, if you run multiple environments (development: development, production: production, test: Testing, etc ..), you can establish independent connection groups for each environment and switch between groups directly. For example, to set up a "test" environment, you can do this:

$ Db ['test'] ['hostname'] = "localhost ";
$ Db ['test'] ['username'] = "root ";
$ Db ['test'] ['Password'] = "";
$ Db ['test'] ['databas'] = "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 ";

Then, tell the system to use the "test" group. You can set the variables in the configuration file:

$ Active_group = "test ";

Note: The name of "test" is arbitrary, which allows you to set it freely. Our main connection uses the name "default" by default. Of course, you can give it a more meaningful name based on your project.

Active Record
The Active Record class can be globally set using the $ active_record variable in the database configuration file (allow/disable TRUE/FALSE (boolean )). if you do not need this class, you can set this variable value to FALSE to reduce the consumption of computer resources during database class initialization.

$ Active_record = TRUE;

Note: Some CodeIgniter classes, such as Sessions, require the support of Active Records when executing some functions.

Parameter Parsing:
Hostname-the host name of the database, which is usually on the local machine and can be expressed as "localhost ".
Username-username to connect to the database.
Password-password used to log on to the database.
Database-name of the database to be connected.
Dbdriver-database type. Such as mysql, ipvs, and odbc. It must be a lowercase letter.
Dbprefix-the prefix of the data table when the ActiveRecord query is run. It allows multiple CodeIgniter programs to be installed in a database.
Pconnect-TRUE/FALSE (boolean)-use persistent connection.
Db_debug-TRUE/FALSE (boolean)-displays database error information.
Cache_on-TRUE/FALSE (boolean)-whether the database query cache is enabled. For more information, see database cache.
Cachedir-absolute path of the server where the cache directory is located in the database query.
Char_set-character set used for communicating with the database.
Dbcollat-character collation used to communicate with the database ).
Port-database port number. Currently, it is only used for ipvs drivers. To use this value, you should add a line of code to the Database Configuration array.
$ Db ['default'] ['Port'] = 5432;

Tip: not all values are required. It depends on the database platform you are using, such as MySQL, S, and so on .) for example, when you use SQLite, you do not need to provide username or password. The database name is the path of your database file. the preceding content assumes that you are using the MySQL database.

Connect to your database
There are two methods to connect to the database:

Automatic Connection
The "Automatic Connection" function will be automatically instantiated when each page is loaded. To enable automatic connection, you can add a database to the library array in the following file:

Application/config/autoload. php

Manual connection
If only a part of the page requires database connection, you can manually add the following code in the function you need or in your class for this class.

$ This-> load-> database ();


If the first parameter of the above function does not have any information, it will be searched in the database configuration file specified by the system. This is the preferred method for most people.

Available Parameters
Database Connection value, transmitted using an array or DSN string.
TRUE/FALSE (boolean ). Whether to return the connection ID (see "connect to multiple databases" below ").
TRUE/FALSE (boolean ). Whether to enable the Active Record class. The default value is TRUE.
Manually connect to a database
The first parameter of the function allows you to specify custom detailed database configuration information from your configuration file. Alternatively, you can submit database connection properties without specifying the configuration file. Example:

To select a specified array from your configuration file, you can do this:

$ This-> load-> database ('group _ name ');

Group_name refers to the name of an array with database connection information in your configuration file.

To manually connect to the required database, you can define the following array:

$ 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 ";

$ This-> load-> database ($ config );

For details about each Configuration Attribute, click here.

Or you can submit the database configuration information in DSN mode. DSN must be implemented in the following ways:

$ Dsn = 'dbdriver: // username: password @ hostname/database ';

$ This-> load-> database ($ dsn );

If you want to overwrite the default configuration when using a DSN string for connection, add the configuration variable as the query string.

$ Dsn = 'dbdriver: // username: password @ hostname/database? Char_set = utf8 & dbcollat = utf8_general_ci & cache_on = true & cachedir =/path/to/cache ';

$ This-> load-> database ($ dsn );

Connect to multiple databases
If you need to connect to more than one database at the same time, you can use the following methods:

$ DB1 = $ this-> load-> database ('group _ one', TRUE );
$ DB2 = $ this-> load-> database ('group _ two', TRUE );

Note: Change "group_one" and "group_two" to specify the group name of the connection attribute (or the array name of the connected array mentioned above ).

Return a database object by setting the second parameter of the function to TRUE (boolean.

When you use this method, you will use the object name to execute the operation command instead of the User Wizard mode, that is, you will execute the database operation in the following ways:

$ DB1-> query ();
$ DB1-> result ();
Etc...

Instead:

$ This-> db-> query ();
$ This-> db-> result ();
Etc...


Reconnect/keep the connection valid
When you are performing some heavyweight PHP operations (such as image processing), if the idle timeout limit of the database server is exceeded, you should consider using reconnect () before executing more queries () method to send the ping command to the server, so that the connection can be elegantly maintained or re-established.

$ This-> db-> reconnect ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.