Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Guestbook {
- private $pdo;
- function __construct()
- {
- $this->pdo = new PDO('mysql:host=localhost;dbname=guestbook_test', 'root', '');
- }
- public function saveGuestbookEntry($author, $email, $message)
- {
- if ($this->validateGuestbookEntry($author, $email, $message) === true) {
- $cursor = $this->pdo->prepare('INSERT INTO guestbook_entries (author, email, message, create_date) VALUES (?, ?, ?, NOW())');
- $cursor->execute(array($author, $email, $message));
- $cursor->closeCursor();
- } else {
- $this->showError('Your input looks incorrect, please check it');
- }
- }
- private function validateGuestbookEntry($author, $email, $message)
- {
- if (
- strlen($author) >= 2 &&
- filter_var($email, FILTER_VALIDATE_EMAIL) &&
- strlen($message) >= 5
- ) {
- return true;
- } else {
- return false;
- }
- }
- private function showError($message)
- {
- echo '<div class="error">' . $message . '</div>';
- }
- public function getGuestbookEntries()
- {
- $cursor = $this->pdo->prepare('SELECT * FROM guestbook_entries ORDER BY create_date DESC');
- $cursor->execute();
- $result = $cursor->fetchAll(PDO::FETCH_ASSOC);
- $cursor->closeCursor();
- return $result;
- }
- }
- $guestbookInstance = new Guestbook();
- if (isset($_POST['submit'])) {
- $guestbookInstance->saveGuestbookEntry($_POST['author'], $_POST['email'], $_POST['message']);
- }
- ?>
- <!doctype html>
- <html>
- <head>
- <meta charset="UTF-8">
- </head>
- <body>
- <section>
- <form action="#" method="post">
- <input type="text" name="author" placeholder="Author"><br>
- <input type="text" name="email" placeholder="Email"><br>
- <textarea name="message" placeholder="Message"></textarea><br>
- <input type="submit" value="Send" name="submit">
- </form>
- </section>
- <section>
- <?php
- $entries = $guestbookInstance->getGuestbookEntries();
- if (count($entries) > 0) {
- foreach ($entries as $entry) {
- echo "<div>";
- echo "<h3>{$entry['message']}</h3>";
- echo "<p>{$entry['author']}</p>";
- echo "</div>";
- }
- } else {
- echo "<p>No entries found.</p>";
- }
- ?>
- </section>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement