I am trying to connect multiple database in my project. Since i am using single database and it’s working properly, now I would like to connect multiple 2 or 3 databse in my exisiting project, which will helpful for me. See my existing project code below for better understanding:
include_once(dirname(__FILE__) . '/config.php');
Class Database{
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct(){
$this->connectDB();
}
private function connectDB(){
$this->link = new mysqli($this->host, $this->user, $this->pass,
$this->dbname);
if(!$this->link){
$this->error ="Connection fail".$this->link->connect_error;
return false;
}
}
}
Here is config.php file, where i will provide my multiple database connection credentials. Hence now here is single information given as I am using.
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_NAME", "db");
I have another file name called main.php where all the query operations functions are written. Here is the sample code:
include_once(dirname(__FILE__) . '/database.php');
class Model
{
private $db;
public function __construct()
{
$this->db = new Database();
}
public function employee_list()
{
$query = "SELECT * FROM emp_list ORDER BY emp_id DESC";
return mysqli_query($this->db->link,$query);
}
}
Now I want to add multiple database with this existing project, so can you tell me whats need to update in this code. Thank you
2
Answers
Since you’ve already initialized the data members in your
Database
class with default values, you can make your constructor optionally accept the connection parameters, for example:This way, only changed values will be updated, so if you have two databases on the same host you can simply pass the
$dbname
parameter and leave the others unchanged.Another solution would be to leave your original code as is without changing it, but to include a different configuration file each time, it would still work fine.
If you were to store all the database connection details in a single file ( as JSON ) you could do something like this.
Testing the above yields:
… output for
$model_2
omitted.With an approach like that you can edit the connection details without needing to modify the classes later and can use any number of different databases if required.