Very Simple Guestbook With PHP MySQL (Free Download)

Welcome to a quick tutorial on how to create a simple guestbook with PHP and MySQL. Once upon a time in the Iron Age of the Internet, guestbooks were commonly seen on blogs, allowing guests to leave short messages. But these days, it seems to have been taken over by comments… Nonetheless, it still has its own old-day charms.

Creating a guestbook with PHP and MySQL only involves a few components:

  • A guest book database table to hold the entries.
  • A PHP library to save and load the guest book entries.
  • Lastly, an actual implementation on the pages themselves.

So if you are looking to put a good old guestbook on your website, let us walk through an example in this guide – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

PHP GUESTBOOK

All right, let us now get into the details of building a PHP MYSQL guestbook.

 

 

 

PART 1) GUEST BOOK TABLE

1-database.sql
CREATE TABLE `guestbook` (
  `post_id` bigint(20) NOT NULL,
  `email` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `comment` text NOT NULL,
  `datetime` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `guestbook`
  ADD PRIMARY KEY (`post_id`,`email`),
  ADD KEY `datetime` (`datetime`);
Field Description
post_id Post ID, primary key.

  • If you want to have multiple guest books or a guest book for different pages, assign a different post_id to each page.
  • If you only want a single guest book for the entire site, then just ignore and fix this to “always use 1”.
email Email of the guest, primary key.
name Name of the guest.
comment The guest book entry itself.
datetime Time of entry. Defaults to the current timestamp.

First, we begin with a simple database table to hold the guestbook entries. This is different from a comment system, in the sense that guests can only write an entry once – With the primary key being the post ID and email. Feel free to change this structure to fit your own requirements.

 

 

PART 2) PHP GUEST BOOK LIBRARY CLASS

2-lib.php
<?php
class GuestBook {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo;
  private $stmt;
  public $error;
  function __construct() {
    $this->pdo = new PDO(
      "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
      DB_USER, DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
    ]);
  }

  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct() {
    $this->pdo = null;
    $this->stmt = null;
  }

  // (C) GET GUEST BOOK ENTRIES
  function get ($pid) {
    $this->stmt = $this->pdo->prepare(
      "SELECT * FROM `guestbook` WHERE `post_id`=? ORDER BY `datetime` DESC"
    );
    $this->stmt->execute([$pid]);
    return $this->stmt->fetchall();
  }

  // (D) SAVE GUEST BOOK ENTRY
  function save ($pid, $email, $name, $comment, $date=null) {
    if ($date==null) { $date = date("Y-m-d H:i:s"); }
    try {
      $this->stmt = $this->pdo->prepare(
        "REPLACE INTO `guestbook` (`post_id`, `email`, `name`, `comment`, `datetime`) VALUES (?,?,?,?,?)"
      );
      $this->stmt->execute([$pid, $email, $name, strip_tags($comment), $date]);
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }
}

// (E) DATABASE SETTINGS - CHANGE TO YOUR OWN !
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (F) NEW GUEST BOOK OBJECT
$_GB = new GuestBook();

With the database in place, the next step is to create a library to work with it. This library is seemingly difficult at first, but keep calm and look carefully:

  • (A, B, F) On creating $_GB = new GuestBook(), the constructor will automatically connect to the database. The destructor closes the connection.
  • (C & D) There are only 2 functions here!
    • get() Get all the guest book entries for the specified post ID.
    • save() Create/update an existing entry.
  • (E) Self-explanatory. Remember to change the database settings to your own.

 

 

PART 3) GUEST BOOK HTML PAGE

3-page.php
<?php
// (A) PAGE INIT
// (A1) LOAD LIBRARY + SET PAGE ID
// GIVE EVERY PAGE A "UNIQUE ID"
// OR JUST USE "1" FOR A SINGLE GUESTBOOK FOR THE ENTIRE SITE
require "2-lib.php";
$pid = 1;
 
// (A2) SAVE GUEST BOOK ENTRY
if (isset($_POST["name"])) {
  if ($_GB->save($pid, $_POST["email"], $_POST["name"], $_POST["comment"])) {
    echo "<div class='note'>Guest Book Entry Saved</div>";
  } else {
    echo "<div class='note'>$_GB->error</div>";
  }
}
 
// (A3) GET GUEST BOOK ENTRIES
$entries = $_GB->get($pid); ?>
 
<!-- (B) GUEST BOOK ENTRIES -->
<div id="gb-entries">
  <?php if (count($entries)>0) { foreach ($entries as $e) { ?>
  <div class="gb-row">
    <img class="gb-ico" src="talk.png">
    <div class="gb-msg">
      <div class="gb-comment"><?=$e["comment"]?></div>
      <div class="gb-name"><?=$e["name"]?></div>
      <div class="gb-date"> &#x2022; <?=$e["datetime"]?></div>
    </div>
  </div>
  <?php }} ?>
</div>
 
<!-- (C) ADD NEW ENTRY -->
<form method="post" target="_self" id="gb-form">
  <textarea name="comment" placeholder="Comment" required></textarea>
  <input type="text" name="name" placeholder="Name" required>
  <input type="email" name="email" placeholder="Email" required>
  <input type="submit" value="Sign Guestbook">
</form>

Lastly, the HTML page itself. This may look a little messy at first, but it’s actually straightforward. It will be easier to study in this order:

  • (C) The “sign guestbook” form itself with 3 fields – Name, email, and comment.
  • (A) We are simply using 2-lib.php to do all the database work here.
    • Save a new guest book entry $_GB->save() when the form is submitted.
    • Then load all the guest book entries for the page $entries = $_GB->get($pid).
  • (B) Generate the HTML for the guest book entries.

 

 

EXTRAS

That’s it for the code, and here are a few small extras that you may find to be useful.

 

SPAM PROTECTION

We cannot simply depend on the “honor system” and trust spammers, haters, and trolls to not spam the guestbook. For added protection, I have 2 recommendations:

 

THE END

Thank you for reading, and we have come to the end of this tutorial. I hope that it has helped you to create a better project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

12 thoughts on “Very Simple Guestbook With PHP MySQL (Free Download)”

    1. As above – Primary key = POST ID + EMAIL. This is not a comment system, guests can only write one entry per post.

  1. Thanks for sharing! Works perfect, and just what i needed for our online chrismas-riddle-wall-of-fame 🙂

    I was getting errors on longer comments, so iv’e changed the “comment” type to “LONGTEXT” in mysql.
    Again, thank you!
    Grtz Frank

Comments are closed.