What is the purpose of encapsulating database functions within a class in PHP?
Encapsulating database functions within a class in PHP helps to organize and manage database operations more efficiently. It allows for better code reusability, easier maintenance, and improved security by restricting direct access to database functions. Additionally, encapsulating database functions within a class can make the code more readable and easier to understand.
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $connection;
public function __construct() {
$this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function fetch($result) {
return $result->fetch_assoc();
}
public function close() {
$this->connection->close();
}
}
// Example of using the Database class
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $db->fetch($result)) {
echo $row['username'] . "<br>";
}
$db->close();