Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

php - OOP database connect/disconnect class

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:Programswebserver
ootoopoop.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", mysqli_connect_error());
            exit();
        }

        $this->mysqli->select_db($this->database);

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
", 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.
", $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 />";
    }
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...