Need help in Database connection OOP way.

Hello users,

I just joined this forum and it seems i will get some help here :slight_smile:

Problem is that i have a database class which holds a connect() method.
Following is the code:

[php]
public function connect($host, $user, $password, $database) {
$this->Host = $host;
$this->User = $user;
$this->Password = $password;
$this->Database = $database;

    $this->Connection = mysql_connect($this->Host,  $this->User,  $this->Password)
            or die('<h1>'.  mysql_error().'</h1>');
    
    if($this->Connection){
        //Selecting the database.
        $this->DbSelected = mysql_select_db($this->Database,  $this->Connection)
                or die('<h1>'.mysql_error().'</h1>');

// if($this->DbSelected){
// echo ā€œconnectedā€;
// }
}
[/php]

I made a config.php file ā€¦
[php]
require_once ā€˜inc.database.phpā€™;
$Database = new Database();
$Database->connect(ā€œlocalhostā€, ā€œaih786_raheelā€, ā€œraheel786ā€, ā€œaih786_basicblogā€);
[/php]

Now the problem is that i am including my config.php file on every page of my application and every time it will be creating Database object again and again which i think is not a good practiceā€¦ I tried to make the connect methods static but its giving me errors which i donā€™t understand. I need help how to avoid making object again and againā€¦ any other approach which i can use to have my connect() method on every page without mulitple connections attempts and multiple object creation.

Thanks and Regards,

Raheel

Sponsor our Newsletter | Privacy Policy | Terms of Service