验证用户后,我需要更改数据库名称。在database.php 文件中有这个。
$db['default'] = array(....
'database' => 'databasename1',
...
);
我知道你可以用 $this->db->database 来显示数据库的值。我想在用户 session 期间将其更改为另一个名称。
我曾尝试使用 $this->db->set_database('databasename2') 和其他各种尝试,但没有解决方案。我也搜索过,找不到解决办法。
任何人都知道如何在用户 session 期间更改数据库名称?
最佳答案
因此您可以从 session 中获取连接详细信息并使用这些详细信息手动连接到数据库并在完成后关闭它
手动连接到数据库
$this->load->database();
此函数的第一个参数可以选择用于从您的配置文件中指定特定的数据库组,或者您甚至可以为未在您的配置文件中指定的数据库提交连接值。例子:
要从您的配置文件中选择特定组,您可以执行以下操作:
$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 必须具有以下原型(prototype):
$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);
手动关闭连接
虽然 CodeIgniter 智能地负责关闭您的数据库连接,但您可以明确地关闭连接。
$this->db->close();
有关连接到多个数据库的更多信息,请阅读此 https://ellislab.com/codeigniter/user-guide/database/connecting.html
关于database - 在 CodeIgniter 3 中动态更改数据库名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30899449/