【问题标题】:How to update table row +1 when element is clicked?单击元素时如何更新表格行+1?
【发布时间】:2015-12-07 19:02:07
【问题描述】:

我正在为问题建立一个投票系统。该网站的访问者可以每天一次或类似地对他们最喜欢的问题进行投票。 当点击特定问题的按钮时,如何 +1 到 QuestionVotes 行?

我的代码:

<?php
    $connection = mysqli_connect('localhost', 'root', '', 'test');
    mysqli_set_charset($connection, 'utf8');
    if (!$connection) {
        die("Database connection failed: " . mysqli_error());
    }
    $sql = "SELECT QuestionHeader, QuestionText, QuestionVotes FROM question ORDER BY QuestionVotes DESC LIMIT 3";
    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
         // output data of each row
         while($row = $result->fetch_assoc()) {
             echo "<div class=\"col-md-4\"><h2>". $row["QuestionHeader"]. "</h2><p>". $row["QuestionText"]. "</p><p><a class=\"btn btn-success\"> " . $row["QuestionVotes"] . "</a></p></div>";
         }
    } else {
         echo "0 results";
    }

    $connection->close();
?>

我想我必须以某种方式存储 QuestionID,然后在单击按钮时检索它,但我不知道如何?以及如何避免人们在同一个问题上投票两次?

【问题讨论】:

    标签: php mysql count row voting


    【解决方案1】:

    好吧,您将需要更改您的数据库表或创建链接在一起并具有一对多关系的附加表,问题表是 1,存储每个 user's vote 的表是多方。

    1. 每个问题都应该有一个唯一的 ID

    2. 如上所示,遍历Questions 表中的问题。每行都应该有一个按钮,当点击该按钮时,会将问题 ID + 用户 ID/(IP 地址 - 如果系统对非注册用户开放)传递给 user's vote 表。

      2a。要在每次唯一用户单击vote 按钮时增加计数,您必须通过Fetchuser's vote 表中获取Count,以查看Question ID 存在多少次。

    3. 但是,在将数据存储到数据库之前,请检查user's vote 表以查看该用户 ID + 问题 ID 是否已经匹配,如果是的话;返回一条消息,告诉用户他们已经对该问题进行了投票(或者您可以花哨并在页面上进行是否检查,如果有匹配项 - 禁用投票按钮)

       $dbname = "DB HERE";
       $servername = "HOST HERE";
       $username = "DB USER HERE";
       $password = "DB PASSWORD HERE";
      
        // Create connection
        $conn = mysqli_connect($servername, $username, $password, $dbname);
      
                       if(isset($_GET['id']))
                  {
                      ///Check to see if user already voted
                      $result = $conn->query("SELECT * FROM User_Votes where user id = $session_id and question_id = $id");
                      $row_cnt = $result->num_rows;
      
                      if($row_cnt < 1)
                      {
                          ///SQL to insert vote into Users Votes table
                      }else
                      {
                          //Vote already exists
                      }
      
                  }
      
                  // Loop through questions for voting
                  $result = mysqli_query($conn,"select * from questions");
                  while($db_questions = mysqli_fetch_object($result))
                  {   
                      echo $db_questions->question_title;
                      echo '- <a href="mypage.php?id=$db_questions->question_id">Click to Vote</a>;
                  }
      

    【讨论】:

    • 感谢您详细描述的答案!我了解您的解决方案并创建一个用户表,这两个表之间的关系将很容易。问题是,我对 PHP 很陌生,老实说,我不太清楚如何循环遍历问题表中的问题,使用 fetch 来获取计数,甚至检查用户 ID 和问题 ID 是否已经匹配,您能否详细说明一下,以便我有希望弄清楚?再次感谢您的回答。
    • @user2304993 - 我将用示例编辑我的答案。我没有测试我为语法错误提供的代码 - 有很多方法可以给猫剥皮,因此可以更好地重写它以更安全和高效。但是......它为您提供了您需要做的事情的基础。我建议去 php.net/manual/en/book.mysqli.php 并做一些阅读。 ——
    • 感谢您的所有时间,我正在努力度过这个缓慢而稳定的过程。不过,我对您从“if(isset($_GET['id']))”中究竟得到了什么感到困惑? question_id / $id 来自哪里?另外,我已关注您的链接,正在阅读您提到的内容,谢谢!
    • @user2304993 - if(isset($_GET['id'])) 正在检查用户是否点击了投票按钮,id 变量将包含用户点击投票的问题的question ID(在浏览器 URL) - 您将创建一个名为 users_vote 的表,其中的一列应该是 question_id,因此当用户单击投票时,您会将 id 插入到 question_id 列中,依此类推.
    • 我会用 $_SERVER['REMOTE_ADDR'] 存储他们的 IP 地址,对吗?再次感谢您,我想我几乎可以使用自己的版本了。
    【解决方案2】:

    您将遇到的最大障碍是识别唯一身份用户。最好的方法是强制注册和登录。那是另一个话题的讨论。

    不管你的表需要有 2 个其他列。

    QuestionID MediumINT (15),无符号,主索引,自动增量。这应该是第一列。

    QuestionVoters 文本,NULL。该字段将保存已投票的用户 ID 的 json 编码数组。 array('123', '38', '27', '15')

    在您的While() 循环中检查用户的ID 是否在QuestionVoters 数组中。

    如果存在,则不要给他们投票操作。否则,使用按钮构建表单以提交到处理页面。

    <?php
    // Need to assign the user's ID to a variable ($userID) to pass to the form.
    $userID = '123'; // this needs to be handled on your end.
    
    // updated sql to include Id and voters
    $sql = "SELECT QuestionID, QuestionHeader, QuestionText, QuestionVotes, QuestionVoters FROM question ORDER BY QuestionVotes DESC LIMIT 3";
    
    while($row = $result->fetch_assoc()) {
    
        $voters = json_decode($row['QuestionVoters'], true); // array of userid's that have voted
        IF (in_array($userID, $voters)) {
            // user has voted
            echo "\n
            <div class=\"col-md-4\">
                <h2>". $row["QuestionHeader"]. "</h2>
                <p>". $row["QuestionText"]. "</p>
                <p>" . $row["QuestionVotes"] . "</p>
            </div>";
        }ELSE{
            // user has not voted
            echo "\n
            <div class=\"col-md-4\">
                <form action=\"vote_processing.php\" name=\"voting\" method=\"post\">
                <input type=\"hidden\" name=\"qid\" value=\"".$row['QuestionID']."\" />
                <input type=\"hidden\" name=\"userid\" value=\"".$userID."\" />
                <h2>". $row["QuestionHeader"]. "</h2>
                <p>". $row["QuestionText"]. "</p>
                <p><button type=\"submit\" value=\"Submit\">" . $row["QuestionVotes"] . "</button></p>
                </form>
            </div>";
        }
    
    }
    ?>
    

    vote_processing.php(示例)

    <?php
    IF (isset($_POST['qid'])) {
    
        $qid = htmlspecialchars(strip_tags(trim($_POST['qid']))); // basic sanitization
        $userid = htmlspecialchars(strip_tags(trim($_POST['userid']))); // basic sanitization
    
        IF ( (is_int($qid)) && (is_int($userid)) ) { // validate that both are integers
    
            // db connection
            $connection = mysqli_connect('localhost', 'root', '', 'test');
            mysqli_set_charset($connection, 'utf8');
            if (!$connection) {
                die("Database connection failed: " . mysqli_error());
            }
    
            // Get voters array
            $sql = "SELECT QuestionVoters FROM question WHERE QuestionID = '".$qid."'";
            $result = $connection->query($sql);
            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    IF (!empty($row['QuestionVoters'])) {
                      // decode users array
                      $voters = json_decode($row['QuestionVoters'], true);
                    }ELSE{
                      $voters = array(); // create array
                    }
                }
                mysqli_free_result($result);
    
                // re-validate the userID "is not" in array
                IF (!in_array($userid, $voters)) { // note the ! [meaning NOT].
    
                    $voters[] = $userid; // add userid to voters array
                    $qvoters = json_encode($voters); // encode voters array
    
                    // update vote
                    $sql_upd = "UPDATE question SET QuestionVotes = QuestionVotes + 1, QuestionVoters = $qvoters WHERE QuestionID = '".$qid."'";
                    $upd_result = $connection->query($sql_upd);
    
                }
    
            }
    
            mysqli_close($connection);
    
        }
    
    }
    
    // redirct back to previous page
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多