如何根据提交的赞成票/反对票表单来增加/减少INT?

问题描述 投票:0回答:1

您好,我正在尝试创建一个带有赞成票/反对票的简单论坛,但我无法获取要提交为“1”或“-1”的值,每次我提交投票时,它都会在“”中提交为“0” vote”列,我将投票列设置为整数(INT)并在我的 PHP 期间也使用 INT,所以我认为这不是问题..

我尝试询问 chatGPT,但我很确定这只会让事情变得更糟/过于复杂,哈哈。

抱歉,如果代码有点长,请告诉我是否需要添加任何额外信息或澄清任何内容。感谢任何帮助,谢谢!

这是我的投票表列:

|编号 |用户名 |用户ID |标题 |描述 |优尼奇 |网址 |投票|类型 |日期 |

这是我的 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;"><small><?php 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 处理提交,它也意味着处理前端的投票增量,但这不起作用,因为表单提交不断向“投票”列提交“0”而不是“1”或“-1”哈哈。

  (function() {
  $(document).ready(function() {
    console.log("Vote Post function is executing.");
    $(".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');
        var buttonElement = $(this); // Store the button element for later use

        // Update the vote count client-side based on the vote action
        var voteCountElement = $("#voteCount-" + postUniqid);
        var currentCount = parseInt(voteCountElement.text());
        if (voteType === 'up') {
            currentCount++;
        } else if (voteType === 'down') {
            currentCount--;
        }
        currentCount = Math.max(currentCount, 0);
        voteCountElement.text(currentCount.toString());

        // Send the AJAX request to update the vote on the server
        var formData4 = {
            'vote': voteType,
            '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) {
                // The server response can still be used for validation and consistency
                console.log("Response received:", 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;
?>
javascript php sql ajax forms
1个回答
0
投票

您的

$vote
似乎仅包含值
up
down
。如果您希望它具有整数值,我建议您像这样更新 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(),
};
© www.soinside.com 2019 - 2024. All rights reserved.