所以,我正在为我的一个客户编写 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
变量有关。
如何解决这个问题,以便我可以正确连接到我的数据库?此外,任何人都可以指出一些文档的方向,我可以学习修复,以便将来解决这个问题。
谢谢!
最佳答案
有很多不同的方法可以编写一个对象来处理对数据库的连接和查询。
最重要的是您要实现的目标。
我认为这些是您希望拥有的一些功能。
- 单一连接
- 运行 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 对象的更多信息,并且在线上有许多关于专门用于管理数据库连接和查询的类的教程。
希望这对您有所帮助!
关于PHP数据库连接类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34968648/