【问题标题】:How to switch to different default database in CodeIgniter?如何在 CodeIgniter 中切换到不同的默认数据库?
【发布时间】:2014-02-09 09:59:57
【问题描述】:

我在数据库配置文件中设置了两个不同的连接。一旦我连接到其中一个数据库,如果我连接到第二个数据库,连接仍然没有改变。我收到 table not found 错误。

$this->load->database(); //connecting to default db
$this->db->query('SELECT * from user'); //user table in default db and no error

$this->load->database('second_db');//connecting to second db
$this->db->load('SELECT * from statistic'); //table exists in second db but getting error
//The same work if I comment the first two lines

【问题讨论】:

标签: php codeigniter codeigniter-2


【解决方案1】:

你可以试试这个方法:

$this->load->database('second_db', TRUE);

并在 database.php 中为 'pconnect' 设置 FALSE: 默认一个:

$db['default']['pconnect'] = FALSE; 

第二个:

$db['second_db']['pconnect'] = FALSE;

【讨论】:

  • @Nish 尝试过这种方式来加载默认数据库:$this->load->database('default', TRUE);
  • 为我工作使用:$second_db = $this->load->database('second_group',TRUE,FALSE);使组保持不变:$db['second_group']['pconnect'] = FALSE;
【解决方案2】:

我自己做了。

$this->load->database(); //connecting to default db
$this->db->query('SELECT * from user'); //user table in default db and no error

$this->load->database('second_db',FALSE,TRUE);//connecting to second db
$this->db->load('SELECT * from statistic'); //table exists in second db but getting error
//The same work if I comment the first two lines

唯一的变化是在加载第二个数据库时需要传递两个额外的参数。 第一个 FALSE - 不返回连接对象 第二个 TRUE - 将活动记录更改为加载的数据库

【讨论】:

    【解决方案3】:

    终于使用 Codeigniter 2.1.0 为我工作:

    $second_db = $this->load->database('second_group',TRUE,FALSE);
    

    使组常量设置'pconnect'为:

    $db['second_group']['pconnect'] = FALSE;
    

    【讨论】:

      【解决方案4】:

      如果你使用

      $this->load->database('second_db', TRUE);
      

      你必须使用like

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

      因为第二个参数 true 返回完整的对象 现在 $db 是您的 db 对象,您可以将 $db 分配给类变量

      $this->second_db = $this->load->database('second_db', TRUE);
      $this->second_db->query();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 2019-12-21
        • 1970-01-01
        • 2016-09-07
        • 2019-04-02
        相关资源
        最近更新 更多