How can a PHP beginner implement a preview feature for a guestbook based on a database?
To implement a preview feature for a guestbook based on a database, the PHP beginner can create a form where users can input their messages. Upon submission, the message can be stored in the database but marked as not yet approved. The guestbook page can then display both approved and unapproved messages, allowing users to preview their messages before they are officially added to the guestbook.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "guestbook";
$conn = new mysqli($servername, $username, $password, $dbname);
// Display guestbook messages
$sql = "SELECT * FROM messages WHERE approved = 1 ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div>";
echo "<p>" . $row["message"] . "</p>";
echo "</div>";
}
} else {
echo "No messages in the guestbook.";
}
// Display form for new message
echo "<form action='submit_message.php' method='post'>";
echo "<textarea name='message'></textarea>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
// Submit message to database
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = $_POST["message"];
$sql = "INSERT INTO messages (message, approved) VALUES ('$message', 0)";
$conn->query($sql);
echo "Message submitted for approval.";
}
$conn->close();
?>
Keywords
Related Questions
- How can the concept of HTTP requests be better understood when working with PHP and JavaScript in web development?
- Are there any best practices for optimizing PHP template systems for performance?
- How can the glob function be utilized to simplify the process of retrieving and sorting file names in PHP?