PHP crash course: Simple Guestbook

MD ARIFUL HAQUE - Jul 30 - - Dev Community

Here's a detailed guide to creating a guestbook application where visitors can leave messages. The implementation will use PHP, AJAX, CSS, and MySQL.

Database Schema

Create a MySQL database and a table for the guestbook messages:

CREATE DATABASE guestbook_db;

USE guestbook_db;

CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    message TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Enter fullscreen mode Exit fullscreen mode

Project Structure

guestbook-app/
├── config.php
├── db.php
├── index.html
├── submit.php
├── fetch.php
├── style.css
├── guestbook.sql
└── js/
    └── main.js
Enter fullscreen mode Exit fullscreen mode

Configure the Database Connection:

  • Open the config.php file and update the database credentials.

     <?php
     // config.php
     $servername = "localhost";
     $username = "yourusername";
     $password = "yourpassword";
     $dbname = "guestbook_db";
    

Configuration File: db.php

<?php
include 'config.php';
// Database configuration
$dsn = 'mysql:host='.$host.';dbname='.$dbname;
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}
?>
Enter fullscreen mode Exit fullscreen mode

Main Page: index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Guestbook</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/main.js" defer></script>
</head>
<body>
    <div class="guestbook-container">
        <h1>Guestbook</h1>
        <form id="guestbook-form">
            <input type="text" id="name" name="name" placeholder="Your Name" required>
            <textarea id="message" name="message" placeholder="Your Message" required></textarea>
            <button type="submit">Submit</button>
        </form>
        <div id="messages-container"></div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

AJAX Script: js/main.js

document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('guestbook-form');
    const messagesContainer = document.getElementById('messages-container');

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(form);

        try {
            const response = await fetch('submit.php', {
                method: 'POST',
                body: formData,
            });
            const result = await response.json();
            if (result.success) {
                form.reset();
                fetchMessages();
            } else {
                alert(result.error);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    });

    async function fetchMessages() {
        try {
            const response = await fetch('fetch.php');
            const messages = await response.json();
            messagesContainer.innerHTML = messages.map(msg => `
                <div class="message">
                    <h3>${msg.name}</h3>
                    <p>${msg.message}</p>
                    <small>${msg.created_at}</small>
                </div>
            `).join('');
        } catch (error) {
            console.error('Error:', error);
        }
    }

    fetchMessages();
});
Enter fullscreen mode Exit fullscreen mode

Submit Message: submit.php

<?php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $message = $_POST['message'];

    if (!empty($name) && !empty($message)) {
        try {
            $stmt = $pdo->prepare('INSERT INTO messages (name, message) VALUES (:name, :message)');
            $stmt->execute(['name' => $name, 'message' => $message]);
            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'All fields are required.']);
    }
}
?>
Enter fullscreen mode Exit fullscreen mode

Fetch Messages: fetch.php

<?php
require 'db.php';

try {
    $stmt = $pdo->query('SELECT name, message, created_at FROM messages ORDER BY created_at DESC');
    $messages = $stmt->fetchAll();
    echo json_encode($messages);
} catch (PDOException $e) {
    echo json_encode([]);
}
?>
Enter fullscreen mode Exit fullscreen mode

CSS Styles: css/style.css

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
}

.guestbook-container {
    max-width: 600px;
    margin: auto;
    background: #fff;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    text-align: center;
    color: #333;
}

form {
    display: flex;
    flex-direction: column;
}

form input,
form textarea {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
}

form button {
    padding: 10px;
    border: none;
    background: #28a745;
    color: white;
    border-radius: 5px;
    cursor: pointer;
}

form button:hover {
    background: #218838;
}

#messages-container {
    margin-top: 20px;
}

.message {
    background: #f9f9f9;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
}

.message h3 {
    margin: 0;
    color: #333;
}

.message p {
    margin: 5px 0 10px;
    color: #666;
}

.message small {
    color: #aaa;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Configuration (config.php): This file contains the database connection setup using PDO. It includes error handling for a failed connection.
  2. Main Page (index.php): The HTML structure of the guestbook, including a form for submitting messages and a container to display messages.
  3. AJAX Script (js/main.js): Handles form submission using AJAX to send data to the server without reloading the page. It also fetches and displays messages dynamically.
  4. Submit Message (submit.php): Processes the form submission, inserts the message into the database, and returns a JSON response indicating success or failure.
  5. Fetch Messages (fetch.php): Retrieves messages from the database and returns them as a JSON array.
  6. CSS (css/style.css): Styles the guestbook application for a clean and user-friendly interface.

This solution ensures that the guestbook application is functional, user-friendly, and adheres to modern web development practices using PHP, AJAX, CSS, and MySQL.

Connecting Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

Source Code

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .