How can PHP be used to create a guestbook functionality on a website?
To create a guestbook functionality on a website using PHP, you can set up a form for users to submit their comments and then store these comments in a database. You can then retrieve and display these comments on the website for other users to see.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "guestbook";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$comment = $_POST['comment'];
// Insert data into database
$sql = "INSERT INTO comments (name, comment) VALUES ('$name', '$comment')";
$conn->query($sql);
}
// Retrieve comments from database
$sql = "SELECT name, comment FROM comments";
$result = $conn->query($sql);
// Display comments
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Comment: " . $row["comment"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- Are there performance advantages or disadvantages between using "utf8_general_ci" and "utf8_unicode_ci" in PHP?
- How can PHP developers ensure that specific conditions are met when generating queries to update a database?
- What best practices should be followed when combining multiple conditions in PHP if statements?