Very Simple Guestbook With PHP & MySQL – Free Source Code

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes The Database PHP Library
Guest Book Page Useful Bits & Links The End

 

DOWNLOAD & NOTES

First, here is the download link to the source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Create a database and import the 1-database.sql file.
  • Change the database settings in 2-core.php to your own.
  • That’s all, launch 3-page.php in your browser.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

THE DATABASE

Let us now start with creating a simple database table to hold all the guest book entries.

 

GUEST BOOK TABLE

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

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.

So yes, the guestbook 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.

 

 

PHP GUEST BOOK LIBRARY

Now that we have established the database table, let us move on to build the PHP library that will work with the database.

 

PHP GUEST BOOK CLASS

2-core.php
<?php
// (A) GUEST BOOK CLASS
class GuestBook {
  // (A1) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo;
  private $stmt;
  public $error;
  function __construct() {
    try {
      $this->pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
      );
    } catch (Exception $ex) {
      die($ex->getMessage());
    }
  }

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

  // (A3) 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(PDO::FETCH_NAMED);
  }

  // (A4) 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, $comment, $date]);
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
    return true;
  }
}

// (B) DATABASE SETTINGS
// ! CHANGE THESE TO YOUR OWN !
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', '');

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

This is seemingly difficult at first, but keep calm and look carefully:

  • Part A is the class GuestBook itself, this is literally the engine behind the guest book.
    • On creating a $_GB = new GuestBook() object, the constructor will automatically connect to the database; The destructor will automatically close the database connection.
    • There are only 2 functions here! function get(POST ID) will get all the guest book entries for the specified post ID, and function save() will create/update an existing entry.
    • That’s all, what this library essentially does is just some SQL queries.
  • Part B & C are self-explanatory. A gentle reminder – Remember to change the database settings to your own.

 

 

GUEST BOOK PAGE

Now that we have all the foundations ready, all that is left is to use it in our front-end HTML pages.

 

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-core.php";
$pid = 1;
 
// (A2) SAVE GUEST BOOK ENTRY
if (isset($_POST['name'])) {
  if ($_GB->save($pid, $_POST['email'], $_POST['name'], $_POST['comment'])) {
    echo "<div>Guest Book Entry Saved</div>";
  } else {
    echo "<div>$_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">
  <div class="gb-datetime"><?=$e['datetime']?></div>
  <div class="gb-name">
    <span class="gb-name-a"><?=$e['name']?></span>
    <span class="gb-name-b">signed:</span>
  </div>
  <div class="gb-comment"><?=$e['comment']?></div>
</div>
<?php }} ?></div>
 
<!-- (C) ADD NEW ENTRY -->
<form method="post" target="_self" id="gb-form">
  <label for="name">Name:</label>
  <input type="text" name="name" required/>
  <label for="email">Email:</label>
  <input type="email" name="email" required/>
  <label for="comment">Comment:</label>
  <textarea name="comment" required></textarea>
  <input type="submit" value="Sign Guestbook"/>
</form>

This may look a little messy at first, but it’s actually straightforward:

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

 

 

THE CSS

4-page.css
/* (A) GUEST BOOK ENTRIES */
.gb-row {
  background: #f5f5f5;
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 10px;
}
.gb-datetime {
  color: #888;
  font-size: 0.9em;
  padding: 5px 0;
}
.gb-name {
  font-weight: bold;
  font-size: 1.2em;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
}
.gb-name-a {
  text-transform: uppercase;
  color: #c32525;
}
.gb-comment { padding-top: 10px; }

/* (B) SIGN GUESTBOOK */
#gb-form {
  margin-top: 20px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  padding: 10px;
}
#gb-form label, #gb-form input, #gb-form textarea {
  display: block;
  box-sizing: border-box;
  width: 100%;
  padding: 8px;
  margin-bottom: 5px;
  resize: none;
}
#gb-form input[type=submit] {
  margin-top: 15px;
  background: #5a69d0;
  color: #fff;
  border: 0;
  padding: 20px 0;
  cursor: pointer;
  font-size: 1em;
}

/* (X) DOES NOT MATTER */
html, body { font-family: arial, sans-serif; }

Just a bunch of cosmetics – Feel free to change these to fit your own theme.

 

 

USEFUL BITS & LINKS

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!

6 thoughts on “Very Simple Guestbook With PHP & MySQL – Free Source Code”

Leave a Comment

Your email address will not be published. Required fields are marked *