I need to achieve the functionality where users can change databases on the fly. Once changed, the current database will be used across all php files making db calls.
So, I am trying to find the best solution to switch and remember the current database params during a single session. This is what I am doing at the moment:
1) php connection files conn1.php, conn2.php, conn3.php etc. containing different database connection parameters (name, password etc - $hostname, $username and so on).
2) when a user changes the database, the current database code is saved as a session variable $currDB.
3) All files that contains db calls, have a db connection switch on the top:
switch ($currDB){
case 1:
require_once('conn1.php');
break;
case 2:
require_once('conn2.php');
break;
........
}
$mysqli = new mysqli($hostname,$username,$password,$database);
Is there a more elegant way of achieving the same functionality of switching databases based on the user selection? I am not sure if maintaining session vars across multiple files would be the best option.
Any better ideas?
Thanks
I recommend, you do something like
(int)
or e.g. is_numeric()
followed by abs(round(..))
on very old PHP versionsnow just @require_once("conn$currentDB.php");
and check for errors.
Last step is to put this into conn.php
and include it from all consumers.
I'd tend to put all the connection details into a single array, included from a single file or some other sort of configuration. Equally, you could also name them, 'live', 'dev', 'live-1', or whatever you like.
$dbDetails = array(
1 => array('hostname' => 'localhost',
'username' => 'blah',
# ... etc ... ),
2 => array('hostname' => 'localhost',
'username' => 'blah',
# ... password & database ... ),
);
if (!isset($currDB, $dbDetails[$currDB])) {
die('unknown DB connection ID');
}
$db = $dbDetails[$currDB];
$mysqli = new mysqli($db['hostname'], $db['username'], $db['password'], $db['database']);