CI连接多个数据库遇到的问题
PS:CI数据库连接两个数据库纠结了好久,按网上说的都已经没错了,但是走不通,看了这篇文章突然明白了,解决办法已经标红。 数据库快速入门例子代码 下面的内容将简单说明怎样使用数据库。更详细的信息请阅读各个函数的单独介绍页面。 初始化数据库类 下面的
PS:CI数据库连接两个数据库纠结了好久,按网上说的都已经没错了,但是走不通,看了这篇文章突然明白了,解决办法已经标红。
数据库快速入门例子代码
下面的内容将简单说明怎样使用数据库。更详细的信息请阅读各个函数的单独介绍页面。
初始化数据库类
下面的代码将依据你的数据库配置载入并初始化数据库类:
$this->load->database();
一旦被载入,你可以在任何地方像这样使用它:
注意: 如果你的所有页面均要求初始化数据库类,你可以让它自动加载。详见 数据库连接。
多结果标准查询(对象形式)
$query = $this->db->query('SELECTname, title, email FROM my_table');
foreach ($query->result() as $row)
{
}
echo 'Total Results: ' .$query->num_rows();
上面的result()函数返回一个对象的数组。例如:$row->title
多结果标准查询(数组形式)
$query = $this->db->query('SELECTname, title, email FROM my_table');
foreach ($query->result_array() as $row)
{
}
上面的result_array()函数返回一个带下标的数组。例如:$row['title']
测试查询结果
如果你的查询可能不返回结果,我们建议你先使用 num_rows()函数来测试:
$query = $this->db->query("YOURQUERY");
if ($query->num_rows() > 0)
{
}
单结果标准查询(对象形式)
$query = $this->db->query('SELECTname FROM my_table LIMIT 1');
$row = $query->row();
echo $row->name;
上面的row()函数返回一个 对象。例如:$row->name
单结果标准查询(数组形式)
$query = $this->db->query('SELECTname FROM my_table LIMIT 1');
$row = $query->row_array();
echo $row['name'];
上面的row_array()函数返回一个 数组。例如:$row['name']
标准插入(insert)
$sql = "INSERT INTO mytable (title, name)
$this->db->query($sql);
echo$this->db->affected_rows();
快捷查询
快捷查询类能为我们提供快速取得数据的途径:
$query =$this->db->get('table_name');
foreach ($query->result() as $row)
{
}
上面的get()函数返回数据表中所有的结果。 快捷查询类 提供所有数据库操作的快捷函数。
快捷插入(insert)
$data = array(
$this->db->insert('mytable',$data);
// Produces: INSERT INTO mytable (title, name, date) VALUES('{$title}', '{$name}', '{$date}')
数据库配置
CodeIgniter 有一个配置文件让你存放数据库连接值(username:用户名,password:密码,databasename:数据库名,等等..). 配置文件位于以下路径:
application/config/database.php
配件文件存放在一个如下格式的一个多维数组里:
$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";
我们使用多维数组的原因是为了让你随意的存储多个连接值的设置。举例:如果你运行多个环境(development:开发、production:制作、test:测试等等..),你能为每个环境建立独立的连接组,并在组直接进行切换。举例,设置一个"test"环境,你可以这样做:
$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";
那么,告诉系统使用"test"组,你可以设置位于配置文件中的变量:
$active_group = "test";
注意:"test"的名字是任意的,这可以让你自由设置,我们的主要连接默认使用"default"这个名字,当然,您可以基于您的项目为它起一个更有意义的名字。
Active Record
Active Record 类 可以通过数据库配置文件里的$active_record变量进行全局的设定(允许/禁止TRUE/FALSE (boolean)).如果你不用这个类,哪么你可以通过将这个变量值设置成FALSE来减少在数据库类初始化时对电脑资源的消耗。
$active_record = TRUE;
注意: 一些CodeIgniter的类,例如Sessions,在执行一些函数的时候需要Active Records的支持。
参数解析:
hostname - 数据库的主机名,通常位于本机,可以表示为"localhost".
username - 需要连接到数据库的用户名.
password - 登陆数据库的密码.
database - 你需要连接的数据库名.
dbdriver - 数据库类型。如:mysql、postgres、odbc等。必须为小写字母。
dbprefix - 当运行ActiveRecord查询时数据表的前缀,它允许在一个数据库上安装多个CodeIgniter程序.
pconnect - TRUE/FALSE (boolean) - 使用持续连接.
db_debug - TRUE/FALSE (boolean) -显示数据库错误信息.
cache_on - TRUE/FALSE (boolean) -数据库查询缓存是否开启,详情请见数据库缓存类。
cachedir - 数据库查询缓存目录所在的服务器绝对路径。
char_set - 与数据库通信时所使用的字符集。
dbcollat - 与数据库通信时所使用的字符规则(character collation)。
port - 数据库端口号. 当前只用于 Postgres 驱动程序. 要使用这个值,你应该添加一行代码到数据库配置数组。
$db['default']['port'] = 5432;
提示: 并不是所有的值都是必须的,这取决与您所使用的数据库平台,如(MySQL, Postgres, 等.) 例如,当你使用SQLite时,你不需要提供username 或 password, 数据库名字就是您数据库文件的路径.以上内容假定您使用的是 MySQL 数据库.
有两种方法连接数据库:
自动连接
“自动连接” 功能将在每个一页面加载时被自动实例化数据库类。要启用“自动连接”,可在如下文件中的 library 数组里添加database:
application/config/autoload.php
手动连接
如果仅仅是一部分页面要求数据库连接,你可以在你有需要的函数里手工添加如下代码或者在你的类里手工添加以供该类使用。
$this->load->database();
如果以上函数的第一个参数没有任何信息,它将会在系统指定的数据库配置文件中寻找,对多数人而言,这是一个首选的方法。
可用的参数
数据库连接值,用数组或DSN字符串传递。
TRUE/FALSE (boolean)。是否返回连接ID(参阅下面的“连接多数据库”)。
TRUE/FALSE (boolean)。是否启用 Active Record 类。默认设置为TRUE。
手动连接到一个数据库
函数的第一个参数能够从你的配置文件中自由的指定你自定义的详细的数据库配置信息。或者你甚至可以不通过指定的配置文件来提交数据库的连接属性。样例:
要从你的配置文件中选择一个指定的数组你可以这么做:
$this->load->database('group_name');
group_name指的是存在于你的配置文件中的带有数据库连接信息的数组的名字。
要手动连接你要求的数据库你可以通过定义以下数组来实现:
$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);
想得到每一个配置属性的详细信息可点击 这里.
或者你可以以DSN的方式提交数据库配置信息。 DSN必然通过以下方式实现:
$dsn = 'dbdriver://username:password@hostname/database';
$this->load->database($dsn);
当用 DSN 字符串连接时,要覆盖配置默认值,则添加配置变量为查询字符串。
$dsn ='dbdriver://username:password@hostname/database?char_set=utf8&dbcollat=utf8_general_ci&cache_on=true&cachedir=/path/to/cache';
$this->load->database($dsn);
连接多数据库
如果你需要同时连接多于一个的数据库,你可以用以下方式来实现:
$DB1 =$this->load->database('group_one',TRUE);
$DB2 =$this->load->database('group_two',TRUE);
注意:改变 "group_one" 和 "group_two" 为你指定了连接属性的组名(或者通过上边说过的连接数组的数组名)。
通过设置函数的第二个参数为TRUE(boolean)来返回一个数据库对象。
当你使用这种方法,你将用对象名来执行操作命令而不是用户向导模式,也就是说,你将用以下方式执行数据库操作:
$DB1->query();
$DB1->result();
etc...
而不是:
$this->db->query();
$this->db->result();
etc...
重新连接 / 保持连接有效
当你正在进行一些重量级的PHP操作(例如处理图片)时,如果超出了数据库服务器的空闲超时限度,你应该考虑在执行更多查询之前使用reconnect()方法来向服务器发送ping命令,这样可以优雅地保持或重新建立连接。
$this->db->reconnect();

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.
