How can PHP variables and database queries be effectively utilized to manage user interactions in a guestbook system within a forum environment?

To manage user interactions in a guestbook system within a forum environment, PHP variables can be used to store user input data and database queries can be utilized to insert, retrieve, and display this data in the guestbook. By using PHP variables to capture user input and database queries to interact with the database, users can leave comments, view existing entries, and interact with other users in the guestbook system effectively.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle user input
if(isset($_POST['submit'])){
    $comment = $_POST['comment'];
    
    // Insert user comment into the database
    $sql = "INSERT INTO guestbook (comment) VALUES ('$comment')";
    
    if ($conn->query($sql) === TRUE) {
        echo "New comment added successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Retrieve and display comments from the database
$sql = "SELECT * FROM guestbook";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Comment: " . $row["comment"]. "<br>";
    }
} else {
    echo "No comments yet.";
}

// Close the database connection
$conn->close();