php 如何根据upvote/downvote表单提交增加INT上/下?

ltqd579y  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(104)

我试图创建一个简单的论坛与upvote/downvote,但我不能得到的值提交为“1”或“-1”,每次我提交一个投票,它被提交为“0”在“投票”列,我有投票列设置为整数(INT),并使用INT在我的PHP太,所以我不认为这是问题。
我试着问ChatGPT,但我很确定这只是让事情变得更糟/过于复杂。
下面是我的投票表列:
| id | username | userID | title | description | uniqid | url | vote | type | date
这是我的HTML/前端页面:

<?php
 // check user session //
 if (isset($_SESSION['usrname'])) {
 $field = "username";
 $value = $_SESSION['usrname'];
 $username = $_SESSION['usrname'];
} else {
 $field = "userID";
 $value = $userID;
 $username = "";
}

// check if the current user has voted the question //
$stmtVoted = $dbh->prepare("SELECT `vote` FROM `votes` WHERE `$field` = :value AND `title` = :title");
$stmtVoted->bindParam(':value', $value, PDO::PARAM_STR);
$stmtVoted->bindParam(':title', $fetch['title'], PDO::PARAM_STR);
$stmtVoted->execute();
$vote = $stmtVoted->fetchColumn();

// count the total user votes for the question //
$stmtVotesTotal = $dbh->prepare("SELECT SUM(`vote`) FROM `votes` WHERE `title` = :title");
$stmtVotesTotal->bindParam(':title', $fetch['title'], PDO::PARAM_STR);
$stmtVotesTotal->execute();
$totalVotes = $stmtVotesTotal->fetchColumn();
?>

// vote form with some information about the question like title, description, URL etc //
<div id="votePostFormContainer-<?php echo $fetch['id'];?>" style="float:right;">
  <form class="vote-post-form" action="" method="POST">
    <input type="hidden" value="<?php echo $fetch['uniqid'];?>" name="postUniqid">
    <input type="hidden" value="Question" name="type">
    <input type="hidden" value="<?php echo $username;?>" name="username">
    <input type="hidden" value="<?php echo $fetch['title'];?>" name="title">
    <input type="hidden" value="<?php echo $fetch['question'];?>" name="description">
    <input type="hidden" value="<?php echo $fetch['url'];?>" name="url">
    <input type="hidden" value="<?php echo $fetch['username'];?>" name="author">
    <input type="hidden" value="<?php echo $userID;?>" name="userID">
    <input type="hidden" value="<?php echo date('Y/m/d H:i:s');?>" name="date">

    <div style="display:flex;">
      <button type="button" class="vote-up-button" data-vote="up">
        <iconify-icon width="18" height="18" icon="<?php echo $vote == 1 ? 'bxs:upvote' : 'bx:upvote'; ?>"></iconify-icon>
      </button>

      <div class="vote-count" id="voteCount-<?php echo $fetch['uniqid'];?>" style="margin-top:-2px;color:#666;"><small><?php if (empty($totalVotes)) {echo '0';} else {echo $totalVotes;}?></small></div>

      <button type="button" class="vote-down-button" data-vote="down">
          <iconify-icon width="18" height="18" icon="<?php echo $vote == -1 ? 'bxs:downvote' : 'bx:downvote'; ?>"></iconify-icon>
      </button>
    </div>
  </form>
</div>

<script type="text/javascript" src="/Blog/resources/voteQuestion.js"></script>

这里是我的voteQuestion.js,用于通过 AJAX 处理提交,它也意味着处理前端的投票增量,但这不起作用,因为表单提交一直向“vote”列提交“0”,而不是“1”或“-1”。

(function() {
$(document).ready(function() {
    $(".vote-up-button, .vote-down-button").on("click", function(e) {
        e.preventDefault();
        var postUniqid = $(this).siblings('input[name="postUniqid"]').val();
        var voteType = $(this).data('vote'); // "up" or "down"
        var buttonElement = $(this); // Store the button element for later use

        // Map voteType to an integer value (+1 for "up" and -1 for "down")
        var voteValue = (voteType === 'up') ? 1 : -1;

        // Find the vote count element and update it
        var voteCountElement = $("#voteCount-" + postUniqid);
        var currentCount = parseInt(voteCountElement.text()) || 0;
        currentCount += voteValue;
        currentCount = Math.max(currentCount, 0);
        voteCountElement.text(currentCount.toString());

        // Update the icons based on the vote action
        var upvoteIcon = '<iconify-icon width="18" height="18" icon="bxs:upvote"></iconify-icon>';
        var downvoteIcon = '<iconify-icon width="18" height="18" icon="bxs:downvote"></iconify-icon';
        
        if (voteType === 'up') {
            // User upvoted, change the icon to the solid upvote icon
            buttonElement.html(upvoteIcon);
            buttonElement.data('vote', 'remove');
        } else if (voteType === 'down') {
            // User downvoted, change the icon to the solid downvote icon
            buttonElement.html(downvoteIcon);
            buttonElement.data('vote', 'remove');
        } else if (voteType === 'remove') {
            // User wants to remove their vote, change the icon back to outline
            buttonElement.html(voteValue === 1 ? upvoteIcon : downvoteIcon);
            buttonElement.data('vote', voteValue === 1 ? 'up' : 'down');
        }

        // Send the AJAX request to update the vote on the server
        var formData4 = {
            'vote': voteValue, // Send the integer value
            'postUniqid': $("input[name='postUniqid']").val(),
            'title': $("input[name='title']").val(),
            'description': $("input[name='description']").val(),
            'type': $("input[name='type']").val(),
            'url': $("input[name='url']").val(),
            'username': $("input[name='username']").val(),
            'userID': $("input[name='userID']").val(),
            'date': $("input[name='date']").val(),
        };

        $.ajax({
            type: "POST",
            url: "/Blog/resources/PHP/voteQuestion.php",
            data: formData4,
            dataType: 'json',
            success: function(response) {
                if (response.hasOwnProperty('voteCount')) {
            // Update the vote count on frontend
            voteCountElement.text(response.voteCount);
            } else {
                console.log("Unexpected response format:", response);
            }

            },
            error: function(xhr, status, error) {
                console.log("AJAX error:", error);
            }
        });
    });
});
})();

这里是我的服务器端PHP,它处理实际的插入、更新、删除行/投票...

<?php
if (isset($_POST['title']) && isset($_POST['username']) && isset($_POST['vote'])) {
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$type = filter_var($_POST['type'], FILTER_SANITIZE_STRING);
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$description = filter_var($_POST['description'], FILTER_SANITIZE_STRING);
$postUniqid = filter_var($_POST['postUniqid'], FILTER_SANITIZE_STRING);
$url = filter_var($_POST['url'], FILTER_SANITIZE_STRING);
$date = filter_var($_POST['date'], FILTER_SANITIZE_STRING);
$userID = filter_var($_POST['userID'], FILTER_SANITIZE_STRING);
$vote = $_POST['vote'];

// Check if the vote already exists for the given user and post
$stmt = $dbh->prepare("SELECT COUNT(*) FROM `votes` WHERE `username` = :username AND `title` = :title AND `uniqid` = :uniqid");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':uniqid', $postUniqid, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();

if ($count > 0) {
    // User has already voted for this post
    // Check the current vote for the user
    $stmt = $dbh->prepare("SELECT `vote` FROM `votes` WHERE `username` = :username AND `title` = :title AND `uniqid` = :uniqid");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':title', $title, PDO::PARAM_STR);
    $stmt->bindParam(':uniqid', $postUniqid, PDO::PARAM_STR);
    $stmt->execute();
    $currentVote = $stmt->fetchColumn();

    if ($currentVote != $vote) {
        // User wants to switch their vote
        $stmt = $dbh->prepare("UPDATE `votes` SET `vote` = :vote WHERE `username` = :username AND `title` = :title AND `uniqid` = :uniqid");
        $stmt->bindParam(':vote', $vote, PDO::PARAM_INT);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':uniqid', $postUniqid, PDO::PARAM_STR);
        $stmt->execute();
    } else {
        // User wants to remove their vote
        $stmt = $dbh->prepare("DELETE FROM `votes` WHERE `username` = :username AND `title` = :title AND `uniqid` = :uniqid");
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':uniqid', $postUniqid, PDO::PARAM_STR);
        $stmt->execute();
    }
} else {
    // Insert a new vote
    $stmt = $dbh->prepare("INSERT INTO `votes` (`title`, `type`, `username`, `userID`, `description`, `uniqid`, `url`, `date`, `vote`) VALUES (:title, :type, :username, :userID, :description, :uniqid, :url, :date, :vote)");
    $stmt->bindParam(':title', $title, PDO::PARAM_STR);
    $stmt->bindParam(':type', $type, PDO::PARAM_STR);
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':userID', $userID, PDO::PARAM_STR);
    $stmt->bindParam(':description', $description, PDO::PARAM_STR);
    $stmt->bindParam(':uniqid', $postUniqid, PDO::PARAM_STR);
    $stmt->bindParam(':url', $url, PDO::PARAM_STR);
    $stmt->bindParam(':date', $date, PDO::PARAM_STR);
    $stmt->bindParam(':vote', $vote, PDO::PARAM_INT);
    $stmt->execute();
}

$stmtCount = $dbh->prepare("SELECT COALESCE(SUM(`vote`), 0) FROM `votes` WHERE `uniqid` = :postUniqid");
$stmtCount->bindParam(':postUniqid', $postUniqid, PDO::PARAM_STR);
$stmtCount->execute();
$voteCount = (int)$stmtCount->fetchColumn();

$response = array('voteCount' => $voteCount);
} else {
$response = array('error' => 'Invalid request');
}

// Output the response as JSON
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>
ffvjumwh

ffvjumwh1#

您的$vote似乎只包含值updown。如果你想让它有一个整数值,我建议你像这样更新你的jQuery formData4对象。

var formData4 = {
   'vote': currentCount,
   'postUniqid': $("input[name='postUniqid']").val(),
   'title': $("input[name='title']").val(),
   'description': $("input[name='description']").val(),
   'type': $("input[name='type']").val(),
   'url': $("input[name='url']").val(),
   'username': $("input[name='username']").val(),
   'userID': $("input[name='userID']").val(),
   'date': $("input[name='date']").val(),
};

相关问题