Codeigniter dynamic database connection

2019-03-01 05:40发布

问题:

I am a beginner at php/OOP and have a question about dynamically changing my database connection.

Here is what my main.php looks like:

class Main extends CI_Controller {

function __construct()
{

    parent::__construct();

    /* Standard Libraries of codeigniter are required */
    $this->load->database($connectdb);
    $this->load->helper('url');
    $this->load->library('grocery_CRUD');
}

public function index()
{


            if ($_POST["username"] == "root")
                    {
                            $connectdb="default";
                    }


                    if ($_POST["username"] == "user1")
                    {
                            $connectdb="default1";
                    }

            if ($_POST["username"] == "user2")
                    {
                            $connectdb="default2";
                    }


    $connect = @mysql_connect("localhost", $_POST["username"], $_POST["password"]);//won't display the warning if any.
    if (!$connect)
    {
            echo 'Server error. Please try again sometime. CON';
    }else{
            print("<a href=\"http://v-admindb/ci/index.php/main/employees?username=".$_POST["username"]."\">Employees</a>");
            echo "<br>";
            print("<a href=\"http://v-admindb/ci/index.php/main/visitors?username=".$_POST["username"]."\">Visitors</a>");
    }//Just an example to ensure that we get into the function
// LOAD LIBRARIES
}

public function employees()
{
    $this->grocery_crud->set_table('employees');
    $output = $this->grocery_crud->render();
    $this->_example_output($output);
}

public function visitors()
{
    $this->grocery_crud->set_table('visitors');
    $output = $this->grocery_crud->render();
    $this->_example_output($output);
}


function _example_output($output = null)

{
    $this->load->view('our_template.php',$output);
}

}

Here is my database.php:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'root';
$db['default']['database'] = 'my_new_cms';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;


//CONNECTION FOR user1
$db['default1']['hostname'] = 'localhost';
$db['default1']['username'] = 'user1';
$db['default1']['password'] = 'user1';
$db['default1']['database'] = 'my_new_cms';
$db['default1']['dbdriver'] = 'mysql';
$db['default1']['dbprefix'] = '';
$db['default1']['pconnect'] = TRUE;
$db['default1']['db_debug'] = TRUE;
$db['default1']['cache_on'] = FALSE;
$db['default1']['cachedir'] = '';
$db['default1']['char_set'] = 'utf8';
$db['default1']['dbcollat'] = 'utf8_general_ci';
$db['default1']['swap_pre'] = '';
$db['default1']['autoinit'] = TRUE;
$db['default1']['stricton'] = FALSE;


//CONNECTION FOR user2
$db['default2']['hostname'] = 'localhost';
$db['default2']['username'] = 'user2';
$db['default2']['password'] = 'user2';
$db['default2']['database'] = 'my_new_cms';
$db['default2']['dbdriver'] = 'mysql';
$db['default2']['dbprefix'] = '';
$db['default2']['pconnect'] = TRUE;
$db['default2']['db_debug'] = TRUE;
$db['default2']['cache_on'] = FALSE;
$db['default2']['cachedir'] = '';
$db['default2']['char_set'] = 'utf8';
$db['default2']['dbcollat'] = 'utf8_general_ci';
$db['default2']['swap_pre'] = '';
$db['default2']['autoinit'] = TRUE;
$db['default2']['stricton'] = FALSE;

When I try logging in I can this error:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: connectdb

Filename: controllers/main.php

Line Number: 12 An Error Was Encountered

You have not selected a database type to connect to.

Changing $this->load->database($connectdb) to 'default', 'default1', or 'default2' makes it work. How do I put a variable in there so that the connect parameters change depending on who is logging in?

Hopefully someone can help, thanks! Eric

回答1:

You should provide the all database information in application/config/database.php´

Normally, you would set the default database group, like so:

$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";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Notice that the login information and settings are provided in the array named $db['default'].

You can then add another database in a new array - let's call it 'anotherdb'.

$db['anotherdb']['hostname'] = "localhost";
$db['anotherdb']['username'] = "root";
$db['anotherdb']['password'] = "";
$db['anotherdb']['database'] = "another_database_name";
$db['anotherdb']['dbdriver'] = "mysql";
$db['anotherdb']['dbprefix'] = "";
$db['anotherdb']['pconnect'] = TRUE;
$db['anotherdb']['db_debug'] = FALSE;
$db['anotherdb']['cache_on'] = FALSE;
$db['anotherdb']['cachedir'] = "";
$db['anotherdb']['char_set'] = "utf8";
$db['anotherdb']['dbcollat'] = "utf8_general_ci";
$db['anotherdb']['swap_pre'] = "";
$db['anotherdb']['autoinit'] = TRUE;
$db['anotherdb']['stricton'] = FALSE;

Now if you want to use the second database, just go

$DB_another = $this->load->database('anotherdb', TRUE); 

and then, instead of $this->db->foo() , you will you $DB_another->foo()

and you can extend this to multiple groups like this

 $DB2 = $this->load->database('anotherdb1', TRUE); 
 $DB3 = $this->load->database('anotherdb2', TRUE); 

For details have a look here: http://ellislab.com/codeigniter/user-guide/database/connecting.html