Codeigniter change database config at runtime

前端 未结 5 1634
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 00:44

Can I change the database config per method in a controller?

$db[\'default\'][\'db_debug\'] = TRUE;

The default is TRUE, while

5条回答
  •  被撕碎了的回忆
    2021-01-03 01:15

    Expanding on the answer by comenk, you can extend the database class and implement various methods by which to achieve your goal.

    First, you'll need to extend the core Loader class by creating a MY_Loader.php file

    class MY_Loader extends CI_Loader
    {
        function __construct()
        {
            parent::__construct();
        }
    
        /**
         * Load the Standard and/or Extended Database function & Driver class
         *
         * @access  public
         * @return  string
         */
        function database( $params = '', $return = FALSE, $active_record = NULL )
        {
            $ci =& get_instance();
    
            if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($ci->db) AND is_object($ci->db))
            {
                return FALSE;
            }
    
            $my_db      = config_item('subclass_prefix').'DB';
            $my_db_file = APPPATH.'core/'.$my_db.EXT;
    
            if(file_exists($my_db_file))
            {
                require_once($my_db_file);
            }
            else
            {
                require_once(BASEPATH.'database/DB'.EXT);
            }
    
            // Load the DB class
            $db =& DB($params, $active_record);
    
            $my_driver      = config_item('subclass_prefix').'DB_'.$db->dbdriver.'_driver';
            $my_driver_file = APPPATH.'core/'.$my_driver.EXT;
    
            if(file_exists($my_driver_file))
            {
                require_once($my_driver_file);
                $db = new $my_driver(get_object_vars($db));
            }
    
            if ($return === TRUE)
            {
                return $db;
            }
    
            // Initialize the db variable.  Needed to prevent
            // reference errors with some configurations
            $ci->db = '';
            $ci->db = $db;
        }
    }
    

    By implementing the above this will allow you to create a MY_DB_mysqli_driver.php whereby mysqli is replaced by whatever driver you're using in your CI database.php config.

    At this point you'd add comenk's answer to MY_DB_mysqli_driver.php

    function debug_on() {
         return $this->db_debug = TRUE;
    }
    
    function debug_off() {
         return $this->db_debug = FALSE;
    }
    
    function in_error() {
         return (bool) $this->_error_number();
    }
    

    Then in your model/controller,

    $this->db->debug_off();
    
    $this->db->query('SELECT * FROM `table`');
    
    if( $this->db->in_error() ) {
        show_404();
    }
    
    $this->db->debug_on();
    

提交回复
热议问题