0

I'm searching a way to create a variable database in Cakephp. I'm creating a website in wich the database setting (user, pass, db) depends of the user who logg's in. The database settings come from another database. Thanks in advance,

Aäron

-- ANSWER

Thanks for your quick reply. I know how to switch between databases, but the database settings have to be variable. Example

   $db = $this->DB_SET['DB_SET']['db']; //from model DB_SET the database 
    $db_login= $this->DB_SET['DB_SET']['login'];
    $db_host= $this->DB_SET['DB_SET']['host'];
    $db_pass= $this->DB_SET['DB_SET']['pass'];
    var $db2 = array(
            'driver' => 'mysql',
            'persistent' => false,
            'host' => $db_host,
            'login' => $db_login,
            'password' => $db_pass,
            'database' => $db,
            'prefix' => '',
            'encoding' => 'UTF8',
            'port' => '',
        );

1 Answer 1

2

If you're looking to create database connections on the fly, you may want to use ConnectionManager::create().

// get logged in user's id and create a connection for them
$id = $this->Auth->user('id');
ConnectionManager::create("user_$id_db", array(
  'driver' => 'mysql',
  'persistent' => false,
  'host' => $db_host,
  'login' => $db_login,
  'password' => $db_pass,
  'database' => $db,
  'prefix' => '',
  'encoding' => 'UTF8',
  'port' => '',
));

Then set your models to use it when you're ready.

// get logged in user's id and use their connection
$id = $this->Auth->user('id');
$this->Model->setDataSource("user_$id_db");
Sign up to request clarification or add additional context in comments.

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.