What are some best practices for handling discussions and voting processes in a PHP forum or community platform?

Issue: Handling discussions and voting processes in a PHP forum or community platform requires proper organization and functionality to ensure a smooth user experience. Code snippet:

// Code for handling discussions and voting processes in a PHP forum or community platform

// Create 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);
}

// Code for displaying discussions
$sql = "SELECT * FROM discussions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Discussion: " . $row["title"]. "<br>";
    }
} else {
    echo "No discussions found";
}

// Code for handling voting process
$discussion_id = 1; // Example discussion ID
$user_id = 1; // Example user ID

// Check if user has already voted
$sql = "SELECT * FROM votes WHERE discussion_id = $discussion_id AND user_id = $user_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "You have already voted for this discussion";
} else {
    // Insert user's vote into database
    $sql = "INSERT INTO votes (discussion_id, user_id) VALUES ($discussion_id, $user_id)";
    if ($conn->query($sql) === TRUE) {
        echo "Vote submitted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

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