【问题标题】:PHP Database connection class issuesPHP数据库连接类问题
【发布时间】:2016-01-23 20:45:12
【问题描述】:

所以,我正在为我的一个客户编写一个 Web 应用程序,我决定将数据库连接保留在一个类中。以下代码是我所拥有的:

class databaseConnection {
    private $hostname = 'hn.app.dev';
    private $username = 'root';
    private $password = '';
    private $database = 'hn_app_dev';
    public function connect() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password);
        if ($host) {
            $connection = mysqli_select_db($host, $this->database);
            if (!$connection) {
                die('An error occured while trying to connect to the database.');
            }
            return $connection;
        }
    }
}

我正在使用mysqli_query 的标准PHP 函数向数据库发送查询。我正在使用以下内容向数据库发送查询:

function fetch_from_db($query) {
    $connection = new databaseConnection();
    $query = mysqli_query($connection->$connection, 'QUERY');
}

我不熟悉在我的代码中使用类。我还在学习,就像我们一样。我已经检查过但找不到解决我的问题的方法。我知道问题出在哪里:这是一个类作为对象的问题,并且与从中获取返回的 $connection 变量有关。

如何解决此问题,以便可以正确连接到我的数据库?另外,谁能指出我可以学习修复的一些文档的方向,以便将来解决这个问题。

谢谢!

【问题讨论】:

  • $connection->connect()
  • @Federico 他使用的是mysqli 函数,而不是mysql
  • 我的错,我看错了

标签: php mysql class


【解决方案1】:

您可以通过多种不同的方式编写对象来处理与数据库的连接和查询。

最重要的是你想要达到的目标。

我认为这些将是您希望拥有的一些功能。

  • 单连接
  • 运行 SQL 并返回 mysqli 结果。
  • 访问连接以转义值。
  • 您似乎希望将凭据存储在它自己的对象中。 (我建议将这些作为值传递给__construct()

这些是一些基本功能,可以轻松扩展。

 class databaseConnection {
    //private $hostname = 'hn.app.dev';
    //private $username = 'root';
    //private $password = '';
    //private $database = 'hn_app_dev';

    private $connection; // this is where the object will store the connection for other methods to access it

    public function __construct($host, $username, $password, $database)
    //public function connect() {
        $this->connection = mysqli_connect($host, $username, $password);
        if ($host) {
            $this->connection->select_db($database); 
            if (!$this->connection) {
                die('An error occured while trying to connect to the database.');
            }
            return $connection;
        }
    }

    // this is so databaseConnection $db can access the connection for escaping MySQLi SQL
    public function connection(){
         return $this->connection;
    }

    function fetch_from_db($query) {
        //$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
        //$query = mysqli_query($connection->$connection, 'QUERY');
        $query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
        return $query; // return the results to the $results var in the bottom example
    }

    // this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
    function __destruct(){
      $this->connection()->close();
    }
}


// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';

// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);

// print the results
while($result = $results->fetch_assoc()){
  print_r($result); // print_r on each row selected from db
}

您可以在手册中了解有关 OOP 和 PHP 对象的更多信息,并且网上有许多关于专门用于管理数据库连接和查询的类的教程。

希望这会有所帮助!

【讨论】:

  • 非常好的和深思熟虑的答案。 +1
【解决方案2】:

如果你打算把它放在一个类中,你永远不要调用connect() 函数。但是,如果您希望在启动类时连接它,请将 connect() 函数更改为 __construct() 并删除 return 并将其分配给公共变量。

class databaseConnection {
    private $hostname = 'hn.app.dev';
    private $username = 'root';
    private $password = '';
    private $database = 'hn_app_dev';
    public $connection;
    public function __construct() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password);
        if ($host) {
            $connection = mysqli_select_db($host, $this->database);
            if (!$connection) {
                die('An error occured while trying to connect to the database.');
            }
            $this->connection = $host;
        }
    }
}

之后,您可以在函数中获取数据库连接,例如:

function fetch_from_db($query) {
    $connection = new databaseConnection();
    $query = mysqli_query($connection->connection, 'QUERY');
}

现在,说了这么多之后,您不想在每个函数中创建一个新实例来访问数据库。因此,可以将其设为静态并创建一个 init() 函数,以便在整个应用程序中占用更少的内存。

对于类文档 PHP 的 Classes/Objects 页面会有所帮助。特别是“示例”链接。

【讨论】:

  • 我得到一个布尔响应,它是'1',而不是连接本身。知道为什么吗?谢谢。
  • 哦,布尔值,因为 mysql_select_db 返回 true 或 false,但仍然适用于原始连接。更新了代码示例。
【解决方案3】:
<?php

class databaseConnection {
    private $hostname = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'onlinylh_sggsfaculty';
    public function connect() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
        if ($host) {
            return $host;
        }
        else{
            echo "Error";
        }
    }
}
function fetch_from_db($query) {
    $conn = new databaseConnection();
    $r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>

这对我有用。

【讨论】:

    猜你喜欢
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2020-04-06
    相关资源
    最近更新 更多