I have this class called dataBase
. Looks like this
class dataBase
{
private $conexion;
private $paisConexion;
var $db;
function __construct($db='default')
{
$this->db = $db;
include '../settings/variables.php';
if(isset($bbdd)){
$conexion = mysql_connect($bbdd["server"], $pais[0]['user'], $pais[0]['pass']) or die('No se pudo conectar: '.mysql_error());
// Seleccionamos la base de datos
mysql_select_db($x[0]['database']) or die('No se pudo seleccionar la base de datos');
if($conexion)
{
$paisConexion = mysql_connect($bbdd["server"], $pais[$this->db]['user'], $pais[$this->db]['pass']) or die('No se pudo conectar: '.mysql_error());
mysql_select_db($pais[$this->db]['database']) or die('No se pudo seleccionar la base de datos');
}
}
else{
echo 'El sistema no se pudo conectar a la base de datos.';
exit;
}
}
public function execute($sql)
{
$result = mysql_query($sql) or die("ERROR: Ejecución de consulta: $sql<br>
");
return $result;
}
}
I am trying to make two connection to two different database using the variable $conexion
and $paisConexion
.
My question is is it possible to do something like this .
I mean suppose I am creating an object for the class like this
$obj = new dataBase(1); $res = obj->execute($sql);
So how the the class will decide which of the connection it has to use ? .
I think I am doing this wrong way . If any one has any idea please let me know
Thanks in Advance
You can't create one class for both databases. Unless you pass some parameter that specifies witch connection to use. Also than you must use two different variables for different connections. And don't use deprecated mysql_*
functions
class DataBase {
// only private variables accessed by functions
private $localDb, $remoteDb;
// Always use constants instead of magic numbers
const LOCAL = 1, REMOTE = 2
public function _construct() {
$this->localDb= new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$this->remoteDb= new PDO('mysql:host=remore;dbname=test2', 'username', 'password');
}
// Can't use constants in function header - - - - -v
public function execute($queryString, $params = [], $useDb = 1) {
// static:: will take variable from this class and not from parent class (if extends something)
if ($useDb == static::LOCAL) {
$db = $this->local;
} elseif ($useDb == static::REMOTE) {
$db = $this->remote;
}
$query = $db->prepare($queryString);
// Usage of prepared statement
return $query->execute($params);
}
}
$db = new DataBase();
$db->execute(
'SELECT * FROM table WHERE column = :columnVal', // named placeholders instead of tons of '?'
[':columnVal' => 5], // some parameters
DataBase::LOCAL // Constant from class
);
Save connection to private field and use it in execute:
function __construct($db='default')
{
...
$this->paisConexion = mysql_connect(...
...
}
public function execute($sql)
{
$result = mysql_query($sql, $this->paisConexion);
return $result;
}
It is possible to do something like this, but the approach you have suggested seems very limited to me, so I have taken the liberty to write an alternative using PDO since the mysql_*
functions are deprecated. Mysql_* functions official documentation here
By using the PDO class provided by PHP you gain the benefit of parameterized queries and transactions. PDO documentation here
To make it easier for you to add other connections in the future I have written a small class containing the absolutely bare bones. I have left many things such as error handling out for simplicity as this only serves as demonstration.
/*
* DO NOT USE THIS IN PRODUCTION
*/
class DatabaseConnectionManager {
private $connections = [];
public function __construct(array $credentials) {
foreach($credentials as $identifier => $information) {
$this->connections[$identifier] = $this->openConnection(
$information['host'],
$information['database'],
$information['username'],
$information['password']
);
}
}
public function __destruct() {
/* If the object is destroyed before the script closes or is disrupted (fatal errors), we
* destroy all database connections as good practice.
*/
$this->connections = [];
}
public function getConnection($identifier) {
if(!array_key_exists($identifier, $this->connections)) {
throw new LogicException('Unknown database connection: ' . $identifier);
}
return $this->connections[$identifier];
}
private function openConnection($host, $database, $username, $password) {
$dsn = "mysql:host{$host};dbname={$database}";
return new PDO($dsn, $username, $password);
}
}
With this you can supply an array of different database connection information. The usage is like the following.
$credentials = [
'primary' => [
'host' => 'localhost',
'database' => 'number1',
'username' => 'awesome',
'password' => 'secret'
],
];
$connections = new DatabaseConnectionManager($credentials);
To get a connection (PDO object) which can perform different database related task, simply specify a connection identifier with the getConnection()
method.
$db = $connections->getConnection('primary');
IMPORTANT
This code is no where near production ready and serve only for demonstration purpose. There is next to no error checking or error handling. If an array with insufficient required parameters is provided you will get an error. At the same time it is impossible at the current moment to provide options to the PDO object without hard-coding them.
Hope this can help you in the right direction.