What are some best practices for storing and accessing values from a database in PHP classes?

When storing and accessing values from a database in PHP classes, it's best practice to separate your database logic from your business logic. One way to achieve this is by creating a separate class dedicated to handling database operations, such as querying, inserting, updating, and deleting data. This class can be instantiated within your business logic classes to interact with the database without cluttering your main class with database-specific code.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

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

    public function insert($table, $data) {
        // Implement insert logic here
    }

    public function update($table, $data, $condition) {
        // Implement update logic here
    }

    public function delete($table, $condition) {
        // Implement delete logic here
    }
}

class User {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        $result = $this->db->query("SELECT * FROM users WHERE id = $id");
        return $result->fetch_assoc();
    }

    public function updateUserEmail($id, $email) {
        $this->db->update("users", ["email" => $email], "id = $id");
    }
}

// Usage
$db = new Database("localhost", "username", "password", "database");
$user = new User($db);
$userData = $user->getUserById(1);
$user->updateUserEmail(1, "newemail@example.com");