<?php namespace libs; trait DataStorage { protected $changed_fields = []; protected int $id; public function get_id() :int { return $this -> id; } public static function get_tablename() :String { return self::$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("`,`", array_keys($this -> data)) . "`"; $values = "'" . implode("','", array_values($this -> data)) . "'"; $tablename = self::get_tablename(); $sql = "INSERT INTO `{$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 { $tablename = self::get_tablename(); $sql = "SELECT * FROM `{$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); $tablename = self::get_tablename(); $sql = "UPDATE `{$tablename}` SET {$fields} WHERE `id`='{$this -> id}' LIMIT 1"; return app() -> db() -> query($sql); } }