⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

Dynamic Database Connection using variables



arbis
  • profile picture
  • Member

Posted 03 October 2013 - 20:15 PM

I am trying to pass a variable into $this->load->database($connectdb)

 

The idea is that a user will log into a webpage and based on the user their database credentials will be located in database.php.  The variable $connectdb will contain the correct login info so that the user can only access specified tables in the database.  Here is my code:

 

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



class Main extends CI_Controller {

    function __construct()
    {

        parent::__construct();

        $this->load->database($connectdb);
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');

    }

    public function index()
    {

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

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

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



        $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);
    }
}
 

 

 

When I try to login I get the 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.

 

 

I'm guessing this has to do with variable scopes but I'm not sure.  I am very new at php/oop in general so any help you can give would be appreciated!

 

Thanks Eric

 

 


briggers
  • profile picture
  • Member

Posted 04 October 2013 - 10:43 AM

Hi,

I don't think you can do things that way. There are a couple of problems, maybe more.

 

A class constructor is executed when the object is instantiated so if you want it to use a variable it must be provided when the class is called. So in your code you would have

$object = new Main($var1, $var2...)

Then your class Main would be defined

class Main ($var1,$var2...)

  protected $_var1;
  protected $_var2;
  .
  .

public function __construct($var1, $var2...)
 {
    $this->_var1 = $var1;
    $this->_var2 = $var2;
    .
    .
  }

//Then define your methods

}

In your case you are trying to use $connectdb before it is given a value

 

--

 

You are not calling the CG class

 

--

 

You seem to be trying to use completely different databases for "employees" and "visitors" rather than different tables in the same database

 

--

 

Your use of "if ($_POST["username"] == "user1")" etc hard codes the users into the code

 

I think you need to think again about the design and maybe read up a bit more on the use of classes in php  :) 


Amit Shah
  • profile picture
  • Member

Posted 10 October 2013 - 12:50 PM

Well.. this is quite possible

i have had a certain scenario earlier long back and have had provided a solution to the same based on the requirement.

 

In order to achieve the system

 

you need to make a certain alterations

1 - in models/grocery_crud_model.php
//add a variable to handle the user db - connection
protected $userDB = null;

2 - in the constructor of the same add the following piece of code
$this->userDB = $this->db;
//This will - by default get hooked to the default database..

3 - add a function 
function setUserDB($db_connection) {
       $CI =& get_instance();
       $CI->userdb =& $this->load->database($userDb, TRUE);
       $this->userDB =& $CI->userdb;
}

4 - all the place in the code where it uses $this->db ... alter it to $this->userdb

//This way we ensure a dynamic connection instead of static connection

5 - now in the GC library  - add a function
public function setUserDBForClient($client_info) {
        $userDb = array();
        $userDb['hostname'] = $client_info[0]['db_hostname'];
        $userDb['username'] = $client_info[0]['db_username'];
        $userDb['password'] = $client_info[0]['db_password'];
        $userDb['database'] = $client_info[0]['db_database'];
        $userDb['dbdriver'] = 'mysql';
        $userDb['dbprefix'] = '';
        $userDb['pconnect'] = FALSE;
        $userDb['db_debug'] = TRUE;
        $userDb['cache_on'] = FALSE;
        $userDb['cachedir'] = '';
        $userDb['char_set'] = 'utf8';
        $userDb['dbcollat'] = 'utf8_general_ci';
        $userDb['swap_pre'] = '';
        $userDb['autoinit'] = TRUE;
        $userDb['stricton'] = FALSE;
        $this->model->setUserDB($userDb);
    }

/// from the controller - the required information about the db login details can now be passed to this function and get the required solution

HAVE NOT TESTED THE SOLUTION - ITS BEEN A LONG LONG TIME BUT FROM WHAT I REMEMBERED - I AM REWRITING THE CODE

Happy GCing :)