Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DB_Record extends Object {
- // protected $db;
- protected $table;
- protected $primaryKey;
- protected $fields;
- // protected $copy;
- public function __construct($table) {
- // $this->db = db::getConnection();
- $this->table = $table;
- $stm = db::query('DESCRIBE ' . $this->table);
- $cols = $stm->fetchAll(PDO::FETCH_OBJ);
- foreach ($cols as $col) {
- if ($col->Key == 'PRI') {
- $this->primaryKey = $col->Field;
- }
- $this->fields[$col->Field] = $col->Default;
- }
- }
- public function load($id) {
- if (preg_match('/^[1-9]\d*$/', $id)) {
- $stm = db::query("SELECT * FROM `{$this->table}` WHERE `{$this->primaryKey}`=$id");
- $data = $stm->fetch(PDO::FETCH_ASSOC);
- if (count($data)) {
- $this->data = $data;
- $this->copy = $data;
- return true;
- }
- }
- return false;
- }
- public function save() {
- // INSERT
- if ($this->isNew()) {
- $fields = $this->matchFields();
- $sql = "INSERT INTO \"{$this->table}\"";
- $sql .= ' ("' . implode('","', array_keys($fields)) . '"")';
- $sql .= ' VALUES (' . substr(str_repeat('?,', count($fields)), 0 , -1) . ')';
- echo $sql . '<br>';
- $stm = db::prepare($sql);
- $stm->execute(array_values($fields));
- return db::lastInsertId();
- }
- // UPDATE
- // if ($this->isChanged()) {
- $fields = $this->matchFields();
- $id = $fields[$this->primaryKey];
- unset($fields[$this->primaryKey]);
- $sql = "UPDATE `{$this->table}` SET ";
- $parts = array();
- foreach ($fields as $k => $v) {
- $parts[] = "`$k`=:$k";
- }
- $sql .= implode(',', $parts) . " WHERE `{$this->primaryKey}`=$id";
- echo $sql . '<br>';
- $stm = db::prepare($sql);
- $stm->execute($fields);
- return (bool) $stm->rowCount();
- // return true;
- // }
- // return false;
- }
- protected function isNew() {
- return !$this->copy;
- }
- // protected function isChanged() {
- // if ($this->copy) {
- // foreach ($this->copy as $k => $v) {
- // if (!isset($this->data[$k]) || $this->data[$k] !== $this->copy[$k]) {
- // return true;
- // }
- // }
- // }
- // return false;
- // }
- protected function matchFields() {
- $ret = array();
- foreach ($this->fields as $field => $default) {
- $ret[$field] = isset($this->data[$field]) ? $this->data[$field] : $default;
- }
- return $ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement