Is it necessary to create a separate class for handling database operations in PHP?
It is not necessary to create a separate class for handling database operations in PHP, but it is a good practice to do so for better organization and reusability of code. By creating a separate class for database operations, you can encapsulate all database-related logic in one place, making it easier to maintain and update in the future.
<?php
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
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();
}
}
?>
Related Questions
- In the context of PHP development, what considerations should be taken into account when modifying text output dynamically based on variables and arrays, as demonstrated in the forum thread?
- Why is it necessary to call session_start() at a specific point when storing objects in the $_SESSION variable?
- What are the potential pitfalls of using file_get_contents() for URLs and how can they be avoided?