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);
?>
Keywords
Related Questions
- How can the use of MD5 encryption enhance the security of user passwords in a PHP login system, even for a small number of users?
- How can one prevent users from resubmitting or altering values in a database when using a button on a PHP page?
- What are the potential pitfalls of using while loops with mysql_fetch_array to populate an array in PHP?