How can classes be effectively used to manage database operations such as adding, deleting, and editing records in PHP?
Classes can be effectively used to manage database operations by creating a class specifically for handling these operations. Within the class, you can define methods for adding, deleting, and editing records in the database. This approach helps to organize your code, improve reusability, and make it easier to maintain and scale your database operations.
class DatabaseManager {
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->conn = new mysqli($host, $username, $password, $dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function addRecord($data) {
// Add record to the database
}
public function deleteRecord($id) {
// Delete record from the database
}
public function editRecord($id, $data) {
// Edit record in the database
}
}
// Example of using the DatabaseManager class
$db = new DatabaseManager("localhost", "username", "password", "dbname");
$db->addRecord($data);
$db->deleteRecord($id);
$db->editRecord($id, $data);