Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Class Essen
*/
class Essen {
protected $Data = [];
/**
* Essen constructor.
* Um ein Objekt zu erstellen
*
* @param null $id
*/
public function __construct($id = null) {
if ($id != null) {
$d = MyDatabase::query("SELECT * FROM `ess_essen` WHERE `id` = " . (int)$id)->fetchAll();
if ($d) {
$this->Data = $d;
}
}
}
/**
* Ein Array mit lauter Essen Objekten
*
* @return Essen[]
*/
public static function getAll() {
$Data = [];
$d = MyDatabase::query("SELECT `id` FROM `ess_essen`");
if ($d) {
foreach ($d as $row) {
$Data[] = new self((int)$row['id']);
}
}
return $Data;
}
/**
* Prüfen ob ein Feld existiert
*
* @param string $key
*
* @return bool
*/
public function exists($key = 'id') {
return array_key_exists($key, $this->Data);
}
/**
* Getter
*
* @param $key
* @param string $alt
*
* @return mixed|string
*/
protected function get($key, $alt = '') {
return $this->exists($key) ? $this->Data[$key] : $alt;
}
/**
* Ausgabe der Daten
*/
public function debug() {
echo "<pre>" . print_r($this->Data, true) . "</pre>";
}
/**
* Gibt ID zurück
*
* @return int
*/
public function getId() {
return (int)$this->get('id');
}
/**
* Gibt den Namen zurück
*
* @return mixed|string
*/
public function getName() {
return $this->get('name');
}
/**
* Name festlegen
*
* @param $value
*/
public function setName($value) {
$this->set('name', $value);
}
/**
* Setter
*
* @param $key
* @param $value
*/
protected function set($key, $value) {
$this->Data[$key] = $value;
}
/**
* Neuen Datensatz erstellen
*
* @return int
*/
public function create() {
$stmt = "INSERT INTO `ess_essen` SET";
$Fields = [];
foreach ($this->Data as $k => $v) {
$Fields[] = "`" . $k . "` = " . MyDatabase::quote($v);
}
$stmt .= implode(', ', $Fields);
return MyDatabase::exec($stmt);
}
/**
* Datensatz updaten
*
* @return int
*/
public function update() {
$stmt = "UPDATE `ess_essen` SET";
$Fields = [];
foreach ($this->Data as $k => $v) {
if ($k == 'id') {
continue;
}
$Fields[] = "`" . $k . "` = " . MyDatabase::quote($v);
}
$stmt .= implode(', ', $Fields);
$stmt .= " WHERE `id` = " . $this->getId();
return MyDatabase::exec($stmt);
}
}
# Alle holen
$All = Essen::getAll();
if ($All) {
# Erstmal alle fetchen und ausgeben
foreach ($All as $Essen) {
$Essen->debug();
}
# Irgendeins nehmen und verändern
$Irgendeins = $All[0];
$Irgendeins->setName("Neuer Name");
$Irgendeins->update();
# Ein neues erstellen
$Neu = new Essen();
$Neu->setName("Neuer Name");
$Neu->create();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment