简体   繁体   English

OOP数据库连接/断开类

[英]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:\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. 我猜这不像在mysql_close函数的括号中放置connectdb方法那么简单,但找不到正确的方法。

Thanks 谢谢

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(). 您需要传递给mysql_close()的是$ this->链接。

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) 添加了__construct($host, $username, $password, $database)
  • Merged connectdb() and select() into __construct() saving an extra two lines of code. connectdb()select()合并到__construct()节省额外的两行代码。
  • Added query($query) 添加了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 编辑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. 正如所指出的那样,mysql已经过时了,因为这个问题仍然定期访问,我想我会发布一个更新的解决方案。

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

你没有从connectdb()返回任何东西但是你正在传递这个函数返回mysql_close()

You should be aware that mysql_* functions were introduced in PHP 4, which is more then 1 yours ago. 你应该知道在PHP 4中引入了mysql_*函数,这些函数已经超过了你的1。 This API is extremely old, and the process has begun to actually deprecating this extension . 此API非常陈旧,并且该过程已开始实际弃用此扩展

You should not in 2012 write new code with mysql_* functions. 您不应该在2012年使用mysql_*函数编写新代码。

There exist two very good alternative : PDO and MySQLi . 有两个非常好的选择: PDOMySQLi Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements . 两者都已经考虑了面向对象的代码,并且它们还使您能够使用预准备语句

That example you showed in the original post written with PDO would look like this: 您在使用PDO编写的原始帖子中显示的示例如下所示:

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

Of course there are more complicated use-case, but the point stand - time to evolve. 当然,有更复杂的用例,但有时间要进化。

mysql_close requires a parameter to disconnect but you are providing nothing. mysql_close需要一个参数来断开连接但你什么也没提供。

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. 面向对象编程与PDO和mysqli配合得很好。 Give it a try 试试看

<?php

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";
        }else{
            return $this->status="Database is connected";
        }
    }
}

$object = new Database();

echo $object->status;

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM