So I have a helper class for connecting to a database but now I want to be able to use the same class to connect to different databases in the same block of code.
Helper Class:
<?php
require_once 'config.php'; // Database setting constants [DB_HOST, DB_NAME, DB_USERNAME, DB_PASSWORD]
class dbHelper {
private $db;
private $err;
function __construct() {
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
try {
$this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
$response["status"] = "error";
$response["message"] = 'Connection failed: ' . $e->getMessage();
$response["data"] = null;
exit;
}
}
function select($table, $where){
try{
$a = array();
$w = "";
foreach ($where as $key => $value) {
$w .= " and " .$key. " like :".$key;
$a[":".$key] = $value;
}
$stmt = $this->db->prepare("select * from ".$table." where 1=1 ". $w);
$stmt->execute($a);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($rows)<=0){
$response["status"] = "warning";
$response["message"] = "No data found.";
}else{
$response["status"] = "success";
$response["message"] = "Data selected from database";
}
$response["data"] = $rows;
}catch(PDOException $e){
$response["status"] = "error";
$response["message"] = 'Select Failed: ' .$e->getMessage();
$response["data"] = null;
}
return $response;
}
}
So you would call the above by setting the constants and then calling the function:
dbconfig.php
<?php
/**
* Database configuration
*/
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'database1');
?>
page.php
<?php
require_once 'dbHelper.php';
$db = new dbHelper();
$rows = $db->select("customers_php",array());
print_r(json_encode($rows,JSON_NUMERIC_CHECK));
?>
I want to drop the need for the config.php file and move the DB_HOST, DB_NAME, etc. to a function inside of the class and pass the database name along with the $table and $where info.
if($db_name == 'database1')
{
//#----------open database connection --------------------> TESTING
$db_host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "database1";
}
if($db_name == 'database2')
{
//#----------open database connection --------------------> TESTING
$db_host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "database2";
}
newpage.php
<?php
require_once 'dbHelper.php';
$db = new dbHelper();
//function select($dbname, $table, $where)......................
$rows = $db->select("database1","customers_php",array());
print_r(json_encode($rows,JSON_NUMERIC_CHECK));
?>
So, where do/can I put the "if($dbname)" part?
query them against each other? I am just curious as you have already accepted the answer you found useful.