diff --git a/Database.php b/Database.php index c286423..8f1a1e6 100644 --- a/Database.php +++ b/Database.php @@ -2,6 +2,7 @@ // connect to MySQL database. class Database { public $connection; + public $statement; public function __construct($config, $username, $password) { @@ -9,8 +10,23 @@ class Database { $this->connection = new PDO($dsn, $username, $password, [PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC]); } public function query($query, $params = []) { - $statement = $this->connection->prepare($query); - $statement->execute($params); - return $statement; + $this->statement = $this->connection->prepare($query); + $this->statement->execute($params); + return $this; + } + public function find() { + return $this->statement->fetch(); + } + public function findOrFail() { + $result = $this->find(); + if (! $result) { + abort(); + } + + return $result; + } + + public function get() { + return $this->statement->fetchAll(); } } \ No newline at end of file diff --git a/controllers/note.php b/controllers/note.php index a062cb7..fb750d7 100644 --- a/controllers/note.php +++ b/controllers/note.php @@ -5,17 +5,14 @@ $config = require('config.php'); $db = new Database($config['database'], $username, $password); $heading = "Note"; +$currentUserId = 1; $note = $db->query('select * from notes where id = :id', [ 'id' => $_GET['id'] -])->fetch(); +])->findOrFail(); + +authorize(($note['user_id'] === $currentUserId)); + -if (!$note) { - abort(); -} -$currentUserId = 1; -if ($note['user_id'] != $currentUserId) { - abort(Response::FORBIDDEN); -} //dd($notes); require "views/note.view.php"; diff --git a/controllers/notes.php b/controllers/notes.php index 4e4ac23..64d6442 100644 --- a/controllers/notes.php +++ b/controllers/notes.php @@ -6,6 +6,6 @@ $heading = "My Notes"; - $notes = $db->query('select * from notes where user_id = 1')->fetchAll(); + $notes = $db->query('select * from notes where user_id = 1')->get(); //dd($notes); require "views/notes.view.php"; \ No newline at end of file diff --git a/functions.php b/functions.php index 52d50c6..f07267d 100644 --- a/functions.php +++ b/functions.php @@ -8,4 +8,10 @@ } function urlIs($value) { return $_SERVER['REQUEST_URI'] === $value; + } + + function authorize($condition) { + if (! $condition) { + abort(Response::FORBIDDEN); + } } \ No newline at end of file diff --git a/views/about.view.php b/views/about.view.php index 91e8778..8c044be 100644 --- a/views/about.view.php +++ b/views/about.view.php @@ -1,12 +1,10 @@ - - - - - - - Now you are on the about page. - - - - - \ No newline at end of file + + + + + + Now you are on the about page. + + + + \ No newline at end of file
Now you are on the about page.