Isaac Gonzalez
Isaac Gonzalez

Reputation: 1734

Select multiple databases with PDO

I have a functions.php file that has one PDO Connection i use to access the database and all that good stuff it's this one:

$host = "localhost";
$db = "maindatabase";
$adminuser = "admin";
$adminpw = "123456";
global $connection;

$connection = new Connection($host,$adminuser,$adminpw,$db);

And i require this script on every file that needs to access to the database, the thing is in some cases i want to change from $db = "maindatabase"; to $db = "anotherdb"; and i know i can do it with just a setter

$connection->setDatabase("anotherdb");

But since i require the functions.php file into every other file i don't know if it will overwrite itself back to default, does anybody knows how can i change it and make it stay ?

EDIT

I have changed require to require_once in my code and since the PHP Documentation says if the file has already been required it will not add it again, do you think this will solve the issue ?

Upvotes: 3

Views: 3015

Answers (3)

Madara's Ghost
Madara's Ghost

Reputation: 174957

This is the classic problem with global variables. Your program state is unpredictable. You can't know which database you're referring to.

Your solution is proper dependency injection.

Implement a factory class to generate the correct database connection on demand, and don't use global variables. That's the correct solution.

Upvotes: 2

Mike Mackintosh
Mike Mackintosh

Reputation: 14237

It may get ugly depending on your level of analness when it comes to pretty code, but why not specifiy the database prefix in your query if the MySQL user has access to both databases?

Example:

SELECT * FROM maindatabase.tablename WHERE this='that';

On your other function, do:

SELECT * FROM anotherdb.tablename WHERE this='that';

You can also do:

$database_name = 'maindatabase';
$query = "SELECT * FROM {$database_name}.table";

$database_name = 'anotherdb';
$query = "SELECT * FROM {$database_name}.table";

This way you can toggle your $database_name variable where needed.

Upvotes: 1

Andrey Vorobyev
Andrey Vorobyev

Reputation: 886

You may make two connections for every database

$host = "localhost";
$db1 = "maindatabase";
$db2 = "anotherdb";
$adminuser = "admin";
$adminpw = "123456";
global $connection1, $connection2;

$connection1 = new Connection($host,$adminuser,$adminpw,$db1);
$connection2 = new Connection($host,$adminuser,$adminpw,$db2);

Upvotes: 2

Related Questions