Can inheritance be utilized when working with database operations?

Yes, inheritance can be utilized when working with database operations to create a more organized and reusable code structure. By creating a base class that handles common database operations and then extending it with specific classes for different tables or entities, you can reduce code duplication and make your code more maintainable.

class BaseDatabase {
    protected $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

    public function query($sql) {
        return $this->connection->query($sql);
    }
}

class UsersDatabase extends BaseDatabase {
    public function getUsers() {
        $result = $this->query("SELECT * FROM users");
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function addUser($name, $email) {
        $name = $this->connection->real_escape_string($name);
        $email = $this->connection->real_escape_string($email);
        
        $this->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
    }
}

// Usage
$usersDb = new UsersDatabase('localhost', 'username', 'password', 'mydatabase');
$users = $usersDb->getUsers();
foreach ($users as $user) {
    echo $user['name'] . ' - ' . $user['email'] . '<br>';
}

$usersDb->addUser('John Doe', 'john@example.com');