<?php namespace libs; trait DataStorage { protected $tablename; protected $changed_fields = []; protected int $id; public function get_id() :int { return $this -> id; } protected function set_tablename(String $tablename) { $this -> tablename = $tablename; } public function get_tablename() :String { return $this -> tablename; } public function get_chanched_fields() :Array { return $this -> changed_fields; } public function create_new() :int { if(count($this -> data_fields) != count($this -> data)) { return 0; } $fields = "`" . implode("`,`", $this -> data_fields) . "`"; $values = "'" . implode("','", array_values($this -> data)) . "'"; $sql = "INSERT INTO `{$this -> tablename}`({$fields}) VALUES ({$values})"; $result = app() -> db() -> query($sql); $this -> id = app() -> db() -> last_insert_id(); return $result; } public function init_by_field(String $field, $val) :bool { $sql = "SELECT * FROM `{$this -> tablename}` WHERE `{$field}`='{$val}'"; $result = app() -> db() -> query($sql); if(!$result or !$result -> num_rows) { return false; } $this -> data = $result -> fetch_assoc(); $this -> id = $this -> data["id"]; return true; } public function update() :bool { if(!count($this -> changed_fields)) { return true; } $fields = []; foreach($this -> changed_fields as $field_name) { $fields[] = "`{$field_name}`='{$this -> data[$field_name]}'"; } $fields = implode(",", $fields); $sql = "UPDATE `{$this -> tablename}` SET {$fields} WHERE `id`='{$this -> id}' LIMIT 1"; return app() -> db() -> query($sql); } }