_primaryKey_ = $this->getPk(); } function __set($name, $value) { $this->_vals_[$name] = $value; } function __get($name) { return isset($this->_vals_[$name]) ? $this->_vals_[$name] : null; } private function getPk() { $res = App::$DB->query("SHOW KEYS FROM " . $this->_tableName_ . " WHERE Key_name = 'PRIMARY'")->fetch(PDO::FETCH_ASSOC); return $res["Column_name"]; } function getByPK($id) { $this->_vals_ = App::$DB->query('SELECT * FROM ' . $this->_tableName_ . ' WHERE ' . $this->_primaryKey_ . ' = ' . $id)->fetch(PDO::FETCH_ASSOC); $this->_id_ = $this->_vals_[$this->_primaryKey_]; return $this; } function getAll() { $res = App::$DB->query('SELECT * FROM ' . $this->_tableName_); $this->_id_ = NULL; // Это больше не конкретная запись $ready = array(); while ($row = $res->fetch(PDO::FETCH_ASSOC)) { $ready[$row[$this->_primaryKey_]] = $row; } return $ready; } function delete($id) { return App::$DB->query('DELETE FROM ' . $this->_tableName_ . ' WHERE ' . $this->_primaryKey_ . ' = ' . $id); } function add($values) { $request = App::$DB->prepare('INSERT INTO ' . $this->_tableName_ . ' (' . implode(',', array_keys($values)) . ') values (:' . implode(', :', array_keys($values)) . ')'); if ( $request->execute((array) $values) ) { return $this->getByPK(App::$DB->lastInsertId()); } else { return false; } } function save() { if (!$this->_id_ || !$this->_vals_) return FALSE; $values = $this->_vals_; unset($values[$this->_primaryKey_]); $request = App::$DB->prepare('UPDATE ' . $this->_tableName_ . ' SET ' . implode('=?, ', array_keys($values)) . '=? WHERE '.$this->_primaryKey_.'='.$this->_id_); $res = $request->execute(array_values($values)); return $res ? $this : FALSE; } function getValues() { return $this->_vals_; } }