user4708809
user4708809

Reputation: 49

Pass variables to a PHP Class Constructor through a class's function

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?

Upvotes: 0

Views: 2177

Answers (1)

fusion3k
fusion3k

Reputation: 11689

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().

Upvotes: 1

Related Questions