OOP database connect / disconnect class

I just started learning the concept of object oriented programming and put together a class to connect to a database, select a database, and close a database connection. So far everything is working fine except for closing the database connection.

    class Database {

    private $host, $username, $password;
    public function __construct($ihost, $iusername, $ipassword){
        $this->host = $ihost;
        $this->username = $iusername;
        $this->password = $ipassword;
    public function connectdb(){
        mysql_connect($this->host, $this->username, $this->password)
            OR die("There was a problem connecting to the database.");
        echo 'successfully connected to database<br />';
    public function select($database){
            OR die("There was a problem selecting the database.");
        echo 'successfully selected database<br />';
    public function disconnectdb(){
            OR die("There was a problem disconnecting from the database.");

$database = new database('localhost', 'root', 'usbw');


When I try to disconnect from the database, I get the following error message:

Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53


I'm guessing it's not as easy as putting the connectdb method in the parentheses of the mysql_close function, but can't find the right way to do it.



source to share

6 answers

I would add the connection / link variable to your class and use the destructor. It also saves you the hassle of having to remember to close your connection, forcing it to do it automatically.
This is the $ this-> link that you need to pass to your mysql_close ().

class Database {

    private $link;
    private $host, $username, $password, $database;

    public function __construct($host, $username, $password, $database){
        $this->host        = $host;
        $this->username    = $username;
        $this->password    = $password;
        $this->database    = $database;

        $this->link = mysql_connect($this->host, $this->username, $this->password)
            OR die("There was a problem connecting to the database.");

        mysql_select_db($this->database, $this->link)
            OR die("There was a problem selecting the database.");

        return true;

    public function query($query) {
        $result = mysql_query($query);
        if (!$result) die('Invalid query: ' . mysql_error());
        return $result;

    public function __destruct() {
            OR die("There was a problem disconnecting from the database.");



Usage example:

    $db = new Database("localhost", "username", "password", "testDatabase");

    $result = $db->query("SELECT * FROM students");

    while ($row = mysql_fetch_assoc($result)) {
        echo "First Name: " . $row['firstname'] ."<br />";
        echo "Last Name: "  . $row['lastname']  ."<br />";
        echo "Address: "    . $row['address']   ."<br />";
        echo "Age: "        . $row['age']       ."<br />";
        echo "<hr />";


So people can actually use the class, I added the missing properties / methods.
The next step is to extend the request method, enable injection protection and any other helper functions.
I made the following changes:

  • Added missing private properties
  • Added __construct ($ host, $ username, $ password, $ database)
  • Combined connectdb () and select () in __construct () saving an extra two lines of code.
  • Added query ($ query)
  • Usage example

Please, if I made a typo or mistake, please leave a constructive comment so I can fix it for others.



you are not returning anything from connectdb()

, but you are returning this function in mysql_close()




You should know that functions mysql_*

were introduced in PHP 4, which is over 1 year ago. This API is very old and the process has started to actually devalue this extension .

You shouldn't write new code with mysql_*

functions in 2012 .

There are two very good alternatives: PDO and MySQLi . Both of them are already written with object oriented code in mind, and they also give you the ability to use prepared statements .

This example, which you showed in the original post written with PDO, would look like this:

//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
$connection = null;


Of course there is a more complex use case, but the waiting point is time for development.



mysql_close requires an option to be disabled, but you don't provide anything.

class Database {

    private $ host, $ username, $ password, $ con;

    public function __construct ($ ihost, $ iusername, $ ipassword) {
        $ this-> host = $ ihost;
        $ this-> username = $ iusername;
        $ this-> password = $ ipassword;
        $ this-> con = false;

    public function connect () {
        $ connect = mysql_connect ($ this-> host, $ this-> username, $ this-> password);
        return $ connect;

    public function connectdb () {
        $ conn = $ this-> connect ();
        if ($ conn)
            $ this-> con = true;
            echo "Successsfully Connected. 
"; return true; } else { echo "Sorry Could Not Connect.
"; return false; } } public function select ($ database) { if ($ this-> con) { if (mysql_select_db ($ database)) { echo "Successfully Connected Database. $ database.
"; return true; } else { echo "Unknown database.
"; } } else { echo "No active Connection.
"; return false; } } public function disconnectdb () { if ($ this-> con) { if (mysql_close ($ this-> connect ())) { $ this-> con = false; echo "Successfully disconnected.
"; return true; } } else { echo "Could Not disconnect.
"; return false; } } } $ database = new database ('localhost', 'root', ''); $ database-> connectdb (); $ database-> select ('databaseoffacebook'); $ database-> disconnectdb ();


Object oriented programming works well with PDO and mysqli. Try




class Database{

    private $link;
    //private $host,$username,$password,$database;
    //private $status;

    public function __construct(){

        $this->host         =   'localhost';
        $this->username     =   'root';
        $this->password     =   '';
        $this->database     =   'workclass';

        $this->link = mysqli_connect($this->host,$this->username,$this->password);

        $this->status = mysqli_select_db($this->link,$this->database);

        if (!$this->status) {
            return $this->status="Failed to Connected with Database";
            return $this->status="Database is connected";

$object = new Database();

echo $object->status;





All Articles