Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7639791
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T08:30:42+00:00 2026-05-31T08:30:42+00:00

I have just started learning the concept of Object oriented programming and have put

  • 0

I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.

    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){
        mysql_select_db($database)
            OR die("There was a problem selecting the database.");
        echo 'successfully selected database<br />';
    }
    public function disconnectdb(){
        mysql_close($this->connectdb())
            OR die("There was a problem disconnecting from the database.");
    }
}

$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();

When I attempt 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 isn’t as simple as placing the connectdb method within the parenthesis of the mysql_close function but can’t find the right way to do it.

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T08:30:44+00:00Added an answer on May 31, 2026 at 8:30 am

    I would add a connection/link variable to your class, and use a destructor.
    That will also save you from haveing to remember to close your connection, cause it’s done automatically.
    It 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() {
            mysql_close($this->link)
                OR die("There was a problem disconnecting from the database.");
        }
    
    }
    

    Example Usage:

    <?php
        $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 />";
        }
    ?>
    

    Edit:
    So people can actually use the class, I added the missing properties/methods.
    The next step would be to expand on the query method, to include protection against injection, and any other helper functions.

    I made the following changes:

    • Added the missing private properties
    • Added __construct($host, $username, $password, $database)
    • Merged connectdb() and select() into __construct() saving an extra two lines of code.
    • Added query($query)
    • Example Usage

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

    edit 23/06/2018

    As pointed out mysql is quite outdated and as this question still receives regular visits I thought I’d post an updated solution.

    class Database {
    
        private $mysqli;
        private $host, $username, $password, $database;
    
        /**
         * Creates the mysql connection.
         * Kills the script on connection or database errors.
         * 
         * @param string $host
         * @param string $username
         * @param string $password
         * @param string $database
         * @return boolean
         */
        public function __construct($host, $username, $password, $database){
            $this->host        = $host;
            $this->username    = $username;
            $this->password    = $password;
            $this->database    = $database;
    
            $this->mysqli = new mysqli($this->host, $this->username, $this->password)
                OR die("There was a problem connecting to the database.");
    
            /* check connection */
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                exit();
            }
    
            $this->mysqli->select_db($this->database);
    
            if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                exit();
            }
    
            return true;
        }
    
        /**
         * Prints the currently selected database.
         */
        public function print_database_name()
        {
            /* return name of current default database */
            if ($result = $this->mysqli->query("SELECT DATABASE()")) {
                $row = $result->fetch_row();
                printf("Selected database is %s.\n", $row[0]);
                $result->close();
            }
        }
    
        /**
         * On error returns an array with the error code.
         * On success returns an array with multiple mysql data.
         * 
         * @param string $query
         * @return array
         */
        public function query($query) {
            /* array returned, includes a success boolean */
            $return = array();
    
            if(!$result = $this->mysqli->query($query))
            {
                $return['success'] = false;
                $return['error'] = $this->mysqli->error;
    
                return $return;
            }
    
            $return['success'] = true;
            $return['affected_rows'] = $this->mysqli->affected_rows;
            $return['insert_id'] = $this->mysqli->insert_id;
    
            if(0 == $this->mysqli->insert_id)
            {
                $return['count'] = $result->num_rows;
                $return['rows'] = array();
                /* fetch associative array */
                while ($row = $result->fetch_assoc()) {
                    $return['rows'][] = $row;
                }
    
                /* free result set */
                $result->close();
            }
    
            return $return;
        }
    
        /**
         * Automatically closes the mysql connection
         * at the end of the program.
         */
        public function __destruct() {
            $this->mysqli->close()
                OR die("There was a problem disconnecting from the database.");
        }
    }
    

    Example usage:

    <?php
        $db = new Database("localhost", "username", "password", "testDatabase");
    
        $result = $db->query("SELECT * FROM students");
    
        if(true == $result['success'])
        {
            echo "Number of rows: " . $result['count'] ."<br />";
            foreach($result['rows'] as $row)
            {
                echo "First Name: " . $row['firstname'] ."<br />";
                echo "Last Name: "  . $row['lastname']  ."<br />";
                echo "Address: "    . $row['address']   ."<br />";
                echo "Age: "        . $row['age']       ."<br />";
                echo "<hr />";
            }
        }
    
        if(false == $result['success'])
        {
            echo "An error has occurred: " . $result['error'] ."<br />";
        }
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just started learning and have put together the form below. The confusion
I have just started learning Objective-C, I am reading Programming in Objective-C 3rd Edition
I have just started learning basics about Graphics2D class, So far I am able
I have just started learning Python & have come across namespaces concept in Python.
I have just started learning about socket programming and learned about winsock and achieved
I have just started learning Erlang and am trying out some Project Euler problems
I have just started learning Jquery and am new to writing javascript (I am
I have just started learning MVVM and having a dilemna. If I have a
I have just started learning NHibernate. Over the past few months I have been
I have just started writing my own JavaScript Framework (just for the learning experience),

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.