What are some best practices for handling INSERT and UPDATE operations with PHP classes representing database tables?

When handling INSERT and UPDATE operations with PHP classes representing database tables, it is best practice to separate the concerns of database interaction from the rest of your application logic. This can be achieved by creating separate methods within your class for inserting and updating data, as well as implementing proper error handling and validation to ensure data integrity.

class User {
    private $db;

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

    public function insertUser($username, $email) {
        $stmt = $this->db->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
        $stmt->bind_param("ss", $username, $email);
        $stmt->execute();
        $stmt->close();
    }

    public function updateUser($userId, $email) {
        $stmt = $this->db->prepare("UPDATE users SET email = ? WHERE id = ?");
        $stmt->bind_param("si", $email, $userId);
        $stmt->execute();
        $stmt->close();
    }
}