What are the best practices for structuring PHP classes to handle database connections in an object-oriented manner?
When structuring PHP classes to handle database connections in an object-oriented manner, it is best practice to create a separate class specifically for managing the database connection. This class should handle establishing the connection, executing queries, and closing the connection. By encapsulating the database connection logic in a separate class, it promotes code reusability, maintainability, and separation of concerns.
<?php
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'my_database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function close() {
$this->conn->close();
}
}
// Example of how to use the Database class
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}
$db->close();
?>