scarecat

How to: guestbook with 000webhost

WARNING: ADVANCED.

For the sake of this tutorial (and lack of my money), my guestbook is using 000webhost for it's backend needs. I'm pretty sure you can use any other hosting solution that has PHP and MySQL.

Let's get started.

1. Setting up 000webhost

1.1. Creating an account

You gotta do it on your own hehe >:). For real though, I don't wanna set up another email just for that (this website allows only a few of email providers onto the site).

1.2. Creating a website on 000webhost

Upon login, simply click on the 'Create new website' button, and follow the guided setup. Wait for your website to be created. That should be all for creating the website!

1.3. Creating a database

To create a database, open your website's dashboard, scroll down until you see 'MySQL Databases', click on it and then 'Create new database'.

Input any database name, username, and password: these will be needed for authentication later on. Notice how the username and database name always get a random id attached to it. (it IS part of the real username)

1.4. Adding a table inside of the database

In the same 'MySQL Databases' section of the dashboard, click the three dots under your newly created database's stats, and press on 'PhpMyAdmin'. This is an UI for managing databases.

In that menu, go to 'Databases', and click on your database (or just click on the database in the side bar).

You should see information about your database's tables (none), and a field 'Create new table'. For the table name I used 'entries' (so you can do the same), and for the amount of columns, I used 5:

If you're feeling adventurous, you can add columns for whatever you like there! (like 'favourite fruit' or 'power level') (ofc you would have to tweak the code a bit)

When clicking create, you will be presented with a table of entries, each row corresponding to one entry. Let's fill them up!

  1. name= id, type= int, A_I(AUTO_INCREMENT)= yes, index= PRIMARY
  2. name= name, type= VARCHAR, length=40
  3. name= content, type= VARCHAR, length=500
  4. name= namecolor, type= VARCHAR, length=7
  5. name= posted_on, type= DATE

If you set it up like that, simply hit 'Save' and you're done! You can still edit the database from PhpMyAdmin, but I won't get into that in the tutorial. We're done here!

2. Setting up PHP

2.1. Adding a PHP file

On your 000webhost website panel, go to File Manager.

Go to the public_html folder, and create a new file called add-guestbook-entry.php. This file will be for storing a new guestbook entry. Fill it up with this code:

// add-guestbook-entry.php
<?php
$servername = "localhost"; // use localhost here
$username = "REDACTED"; // here goes your database username 
$password = "REDACTED"; // here goes your database password
$database = "REDACTED"; // here goes the database name

try {
    // just copy that, it sets up a PDO, object that interfaces with the database.
    $pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // this contains an SQL INSERT QUERY, (the question marks means that we will provide this later)
    // CURDATE() basically just returns the current date, so we don't need to provide a value later
    $insertquery = "INSERT INTO entries (name, content, namecolor, posted_on) VALUES (?,?,?, CURDATE())"; 
    
    // this 'prepares' the query for use
    $prepared = $pdo->prepare($insertquery);

    // this executes the query that inserts the data, notice how we pass an array of values to represent our '?')
    $prepared->execute([$_POST["name"], $_POST["content"], $_POST["namecolor"]]);

    // this tells the browser to go back to this website after
    header("Location: https://yourwebsite.neocities.org/guestbook");
    // and finally exits
    exit();
} catch(PDOException $e) {    
    echo "Connection failed: " . $e->getMessage();
}

Whew! That's a lot at once, just take a small look and replace the values needed!

The next file, we'll call get-guestbook-entries.php, and it will return our entries as JSON (we can easily use json in javascript).

// get-guestbook-entries.php
<?php
$servername = "localhost"; // use localhost here
$username = "REDACTED"; // here goes your database username 
$password = "REDACTED"; // here goes your database password
$database = "REDACTED"; // here goes the database name

try {
    // just copy that, it sets up a PDO, object that interfaces with the database.
    $pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $getquery = "SELECT * FROM entries;"; // query to select
    $q = $pdo->query($getquery); // preparing the query
    $data = $q->fetchAll(PDO::FETCH_ASSOC); // fetch all data as an associative table (with string keys)
    echo json_encode($data); // print out json for that table (we will make a javascript object out of it)
    exit();
} catch(PDOException $e) {    
    echo "Connection failed: " . $e->getMessage();
}

I know this is very confusing, okay, if you have any questions feel free to contact me!

3. Putting the Javascript in place

Add entry form:

Remember to put your username!

Also: styles not included! :p

Notice how every input has a name, that gets added to the $_POST on the php side!

<form action="https://USERNAME.000webhostapp.com/add-guestbook-entry.php" method="post">
  <div class="form-field">
    <label for="name">name (40 chars):</label>
    <input type="text" id="name" name="name" required>
  </div>
  <div class="form-field">
    <label for="namecolor">name color:</label>
    <input type="color" id="namecolor" name="namecolor" value="#ffffff">
  </div>
  <div class="form-field">
    <label for="content">message (500 chars):</label>
    <textarea id="content" required name="content" rows="5"></textarea>
  </div>
  <button type="submit">send</button>
</form>

Now for the javascript (this one is pretty short and sweet)

let container = document.querySelector("#entries");
// a value for a 
fetch("https://USERNAME.000webhostapp.com/get-guestbook-entries.php") //
  .then(res => res.json()) // interprets the data as json, creating us a nice table with all the entries as objects! :3
  .then(data => { 
    // for every entry
    for (let entry of data) {
      // create div
      let elem = document.createElement("div"); 
      //set class name
      elem.className = "entry"; 
      //set border-color to namecolor
      elem.style.borderColor = entry.namecolor; 
      //put data from the entry as html in the div
      elem.innerHTML = `<time class="posted-on" datetime="${entry.posted_on}">${entry.posted_on}</time><h3 class="nametag" style="color: ${entry.namecolor};">${entry.name}</h3><p>${entry.content}</p>`; 
      //add the div
      container.appendChild(elem);
    }
  })

THE END

This post will probably not be public unless I add more explanations and make it more readable, but welp, im running out of time here heh

Again, if you have questions, feel free to contact me, I will explain what anything here does.

So yeah, I hope you find this in any way usable, see ya