db = $db; // store Cache class instance $this->cache = Cache::getInstance(); if ($table !== '') { $this->table = $table; } } // get all rows from specified table public function fetchAll() { // if the cache file is valid fetch records from cache file if ($this->cache->valid($this->table)) { return $this->cache->get($this->table); } else { // otherwise fecth records from database table $rows = array(); $this->db->query('SELECT * FROM ' . $this->table); while ($row = $this->db->fetch()) { $rows[] = $row; } // save data set to cache file $this->cache->set($this->table, $rows); return $rows; } } // update/insert row public function save(array $data, $id = NULL) { if (!empty($data)) { // quote strings foreach ($data as $field => $value) { $value = mysql_escape_string($value); if (!is_numeric($value)) { $data[$field] = '\'' . $value . '\''; } } // update row if ($id !== NULL) { $set = ''; foreach($data as $field => $value) { $set .= $field .'=' . $value . ','; } $set = substr($set, 0, -1); $this->db->query('UPDATE ' . $this->table . ' SET ' . $set . ' WHERE id=' . (int)$id); } // insert new row else { $fields = implode(',', array_keys($data)); $values = implode(',', array_values($data)); $this->db->query('INSERT INTO ' . $this->table . ' (' . $fields . ')' . ' VALUES (' . $values . ')'); } } } // delete row public function delete($id = NULL) { if ($id !== NULL) { $this->db->query('DELETE FROM ' . $this->table . ' WHERE id=' . (int)$id); } } }// End Model class