Tibo
Tibo

Reputation: 91

Switch database with Idiorm

I am trying to generalize a php script using Idiorm. The idea is : the user lands on an auth page. Credentials are stored in a first database, called 'db_users'. For each user stored in 'db_users', I have the following fields : login / password / authorized_db. Once the user is identified, I want to switch the DB set for Idiorm requests to the new one corresponding to its rights.

Example:

config.php 
$db_host        = 'localhost';
$db_user       = 'user1';
$db_password    = 'user1';
$db_name        = 'db_users';

Idiorm is initially configured like this:

ORM::configure("mysql:host=$db_host;dbname=$db_name");
ORM::configure('username', $db_user);
ORM::configure('password', $db_password);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
ORM::configure('return_result_sets', true);

Finally, on the login.php page, I tried something like this, but the ORM information are not updated and the database opened keeps being the first one, db_users and not the one authorized for this user:

if($username != '' AND $password != ''){
  $d = ORM::for_table('users')->where('username',$username)->find_one();
   if($d){
       $the_new_db = $d['authorized_db'];
       ORM::configure("mysql:host=$db_host;dbname=$the_new_db");
       do_something_in_the_new_db();
   }
}

Upvotes: 0

Views: 413

Answers (2)

Angel M.
Angel M.

Reputation: 2732

you need 2 configurations:

1)

ORM::configure("mysql:host=$db_host;dbname=$db_name", null, 'firstDb');
ORM::configure('username', $db_user);
ORM::configure('password', $db_password);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
ORM::configure('return_result_sets', true);

2)

ORM::configure("mysql:host=$db_host;dbname=$db_name2", null, 'secondDb');
ORM::configure('username', $db_user);
ORM::configure('password', $db_password);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
ORM::configure('return_result_sets', true);

Making queries:

if($username != '' AND $password != ''){
  $d = ORM::for_table('users', 'firstDb')->where('username',$username)->find_one();
   if($d){
       $d = ORM::for_table('whichever_table', 'secondDb')->where('user_id', 1)->find_one();
   }
}

Upvotes: 0

Celestz
Celestz

Reputation: 311

You should check out the Multiple Connections section of the documentation, it details how multiple connections can be achieved by naming them.

https://idiorm.readthedocs.io/en/latest/connections.html

Upvotes: 1

Related Questions