2

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:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

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
  • if you going to work with codeigniter then read some manual first ... Commented Oct 2, 2013 at 19:42

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

I only have one database with multiple tables. It appears that what you have above would only work for different databases. Is there a way to dynamically change the database connection in the main.php?
0
$this->load->database($connectdb);

The problem is here, you load this variable in the constructor that you set in your index function.

__constructor() is fired before index() so i guess you should do something like this:

class Main extends CI_Controller {
private $connectdb;

function __construct()
{

    parent::__construct();

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

public function _setConnectdb()
{
if ( $_POST["username"] == "root" ) {
    $this->connectdb = "default";
}

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.