public function insert() { if (!$this->isNew()) { return; } $columns = []; $values = []; foreach ($this as $k => $v) { if ('id' == $k) { continue; } $columns[] = $k; $values[':' . $k] = $v; } var_dump($values); $sql = ' INSERT INTO ' . static::TABLE . ' (' . implode(',', $columns) . ') VALUES (' . implode(',', array_keys($values)) . ') '; $db = Db::instance(); $db->execute($sql, $values); }
public function delete() { if ($this->isNew()) { return false; } $sql = 'DELETE FROM ' . static::TABLE . ' WHERE ' . static::PK . ' = ' . $this->getPk(); $db = Db::instance(); $db->execute($sql); }
public static function getLastNews($count = 3) { $db = Db::instance(); $query = 'SELECT * FROM ' . static::TABLE . ' ' . 'ORDER BY date_create DESC ' . 'LIMIT ' . (int) $count; $result = $db->query($query, [], static::class); if (!empty($result)) { return $result; } return false; }
/** * Метод удаляет запись из таблицы */ public function delete() { if ($this->isNew() || $this->isDeleted()) { return false; } $sql = 'DELETE FROM ' . static::TABLE . ' WHERE id=:id;'; $data = [':id' => $this->id]; $db = \App\Db::instance(); $res = $db->execute($sql, $data); if ($res) { $this->isDeleted = true; } return $res; }
<?php require __DIR__ . '/../tests.php'; $db = \App\Db::instance(); /** * Check execute method if it returns false (row with id does not need to exist in database) */ echo check($db->execute("UPDATE users SET name = 'Петр Петров' WHERE id = 7"), 'Db->execute method without data params'); echo check($db->execute("UPDATE users SET name = 'Петр Петров' WHERE id = :id", ['id' => 7]), 'Db->execute method with data params'); /** * Check query method if it returns non zero array (row with id should exists in database table) */ echo check($db->query("SELECT * FROM users WHERE id = 1", '\\App\\Models\\User'), 'Db->query method without data params'); echo check($db->query("SELECT * FROM users WHERE id = :id", '\\App\\Models\\User', ['id' => 1]), 'Db->query method with data params');