0

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?

4
  • Which databases i.e. mysql - others?. Are the databases on the same server? And do you want to query them against each other? I am just curious as you have already accepted the answer you found useful. Commented Feb 13, 2016 at 19:03
  • The databases are on the same server, for now anyways. If one got rather large, we might consider moving it to its own server. Commented Feb 13, 2016 at 22:35
  • And no, no need to query against each other at this time. Commented Feb 13, 2016 at 22:36
  • Thanks for clarifying that - it helps. Commented Feb 13, 2016 at 22:58

1 Answer 1

1

You can put your if($dbname) part into config.php, then modify your dbHelperclass in this way:

class dbHelper
{
    public function __construct( $db_host, $db_user, $db_password, $db_name )
    {
        (...)
    }
    (...)
}

and call it in this way:

$db = new dbHelper( $db_host, $db_user, $db_password, $db_name );

Edit:

I think may be better to maintain one instance for each connection, but - if you want change it on the fly - you can modify you class as:

class dbHelper 
{
    function __construct( $db_host, $db_user, $db_password, $db_name )
    {
        $this->connect( $db_host, $db_user, $db_password, $db_name );
    }

    function dbSelect( $db_host, $db_user, $db_password, $db_name )
    {
        if( $this->db ) $this->db = Null;
        $dsn = 'mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8';
        try {
            $this->db = new PDO($dsn, $db_user, $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;
        }
    }

    (...)

}

And then change database connection through dbHelper->dbSelect().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.