【问题标题】:switching databases in codeigniter 3在 codeigniter 3 中切换数据库
【发布时间】:2017-10-05 11:15:48
【问题描述】:

我正在尝试为不同的组织/用户使用/更改数据库。在 master 数据库中,我有不同组织的 db_name,我使用以下代码将 db_name 存储在会话中。

$condition = "subdomain =" . "'" . $data['subdomain'] . "' AND " . "status =1";

$this->db->select('id, db_name');
$this->db->from('sublogin');
$this->db->where($condition);
$this->db->limit(1);

$db_name = $this->db->get()->row()->db_name;

// SET db_name for session
$this->session->set_userdata('db_name', $db_name);

在另一个模型中,切换数据库

$db_name = $this->session->userdata('db_name');
$this->db->db_select($db_name); 

它在本地主机上工作,但不在我的实时服务器上,它给出了错误:

发生数据库错误 错误号:1146 表 'db694230824.users' 不存在

我试图回显当前数据库,它说数据库没有改变。

echo $this->db->database;
die(); 

【问题讨论】:

  • 您的数据库用户是否拥有能够访问这两个数据库的正确权限?
  • 让我检查权限。
  • 你运气好吗?
  • 不,支持将在 48 小时内回复。它在我的本地主机上工作正常,所以我认为它的权限问题正如你提到的。所以,我需要等他们。
  • 我在这里很不走运,我所有的问题都没有答案,并且有(-)负分。

标签: php mysql codeigniter codeigniter-3


【解决方案1】:

1 个解决方案。

您可以像这样使用多个数据库:

$this->db = $this->load->database('default', TRUE);
$this->anotherDb = $this->load->database('anotherDb ', TRUE);

或者,如果您分配 codeigniter 超级对象:

public function __construct($params) {

   $this->CI = & get_instance();
   $this->CI->db = $this->CI->load->database('default', TRUE);
   $this->CI->anotherDb = $this->CI->load->database('anotherDb', TRUE);
}

2个解决方案

它之前工作过,不能 100% 确定它是否仍然工作,但看起来这个错误仍然存​​在于 CI 中。 只需在 /system/database/DB_driver.php 文件中的 simple_query 函数处添加 1 行代码:

public function simple_query($sql)
{
    if ( ! $this->conn_id)
    {
        $this->initialize();
    }

    $this->db_select(); // add this
    return $this->_execute($sql);
}

它应该允许您在这样的模型中使用其他数据库:

$this->anotherDb = $this->load->database('anotherDb', true);

不要忘记在 /application/config/database.php 文件中添加其他数据库连接设置,方法与使用默认数据库类似:

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    ...
);

$db['anotherDb'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    ...
);

CodeIgniter » Docs » Database Reference » Connecting to your Database

【讨论】:

  • 感谢您的回答,这将是我的第二个选择,作为 $this->db_select(mydb);在本地主机中对我来说工作正常。我也在等待托管公司回复并授予 dbuser 在其他数据库上的权限。
  • 仍在等待托管公司。使用此解决方案,我将需要定义每个数据库,并且我的应用程序将有多个数据库,可能是 100。所以,我认为我必须使用 db_select()。
  • 是的,第二个解决方案可能更舒适,并提供灵活的选择。但是,一切都取决于您的应用程序的设计。在某些情况下,1 个解决方案可能会更好。
  • 我不想硬编码我的数据库名称,因为我的应用程序中会有更多的数据库。 1 个学校的 1 个数据库。
  • 实现了第一种解决方案,也使用了动态数据库名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2019-04-02
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多