How can the PHP code for a guestbook be optimized for better performance and readability?

To optimize the PHP code for a guestbook for better performance and readability, you can separate the logic into functions, use prepared statements to prevent SQL injection, and implement pagination to limit the number of entries displayed on each page.

<?php
// Function to connect to the database
function connectDB() {
    $db = new PDO('mysql:host=localhost;dbname=guestbook', 'username', 'password');
    return $db;
}

// Function to add a new entry to the guestbook
function addEntry($name, $message) {
    $db = connectDB();
    $stmt = $db->prepare("INSERT INTO entries (name, message) VALUES (?, ?)");
    $stmt->execute([$name, $message]);
}

// Function to display entries with pagination
function displayEntries($page = 1, $limit = 10) {
    $db = connectDB();
    $offset = ($page - 1) * $limit;
    $stmt = $db->prepare("SELECT name, message FROM entries ORDER BY id DESC LIMIT ?, ?");
    $stmt->bindParam(1, $offset, PDO::PARAM_INT);
    $stmt->bindParam(2, $limit, PDO::PARAM_INT);
    $stmt->execute();
    $entries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($entries as $entry) {
        echo "<strong>{$entry['name']}</strong>: {$entry['message']}<br>";
    }
}

// Usage
addEntry('John Doe', 'Hello, world!');
displayEntries(1, 10);
?>