使用左连接在while循环中获取数据

时间:2017-11-08 17:19:57

标签: javascript php jquery ajax

我使用while循环从mysql表中获取用户注释,并希望在注释div中给出的按钮上添加一些条件类。

每条评论都有两个按钮:

  1. thumbsup button
  2. thumbsdown button
  3. 如果用户已经提及任何评论,我想提供一个班级名称有效,以防将来点击相同评论的拇指向上,它会反转该号码喜欢。

    我正在讨论这两个表

    评论

    const data = [{
      title: "Node 1",
      childNodes: [
        { title: "Childnode 1.1" },
        {
          title: "Childnode 1.2",
          childNodes: [
            {
              title: "Childnode 1.2.1",
              childNodes: [
                { title: "Childnode 1.2.1.1" }
              ]
            }, { title: "Childnode 1.2.2" }
          ]
        }
      ]
    }];
    
    const App = () => (
      <form>
        <Tree data={data} />
      </form>
    );
    
    const Tree = ({data}) => ( 
      <ul>
        {data && data.map(item => (
          <li>
            {item.title}
            {item.childNodes && <Tree data={item.childNodes} />}
          </li>
        ))}
      </ul>
    );
    

    likesordislikes

    +----+--------+---------------+---------+
    | id | userid |   usercom     | comname |
    +----+--------+---------------+---------+
    | 35 |      5 | check comment |      12 |
    | 36 |      6 | comment test  |      12 |
    | 37 |      6 | third comment |      12 |
    | 38 |      5 | number four   |      12 |
    | 39 |      7 | fifth         |      13 |
    | 40 |      4 | 6th           |      13 |
    | 41 |     18 | seven         |      13 |
    +----+--------+---------------+---------+
    

    我从这些表中获取数据并在此处回应......

    +----+-------+------+-------+
    | id | vtype | uid  | comid |
    +----+-------+------+-------+
    |  1 |     0 |    5 |    35 |
    |  2 |     1 |    6 |    35 |
    |  3 |     1 |    7 |    35 |
    |  4 |     0 |    8 |    36 |
    |  5 |     1 |    5 |    36 |
    |  6 |     1 |    9 |    35 |
    |  7 |     1 |   10 |    36 |
    |  8 |     1 |   11 |    36 |
    |  9 |     1 |   20 |    35 |
    | 10 |     0 |    9 |    35 |
    | 11 |     1 |   21 |    37 |
    +----+-------+------+-------+
    
    .vbtn {
      display: inline-block;
      margin-bottom: 0;
      font-size: 13px;
      font-weight: 300;
      white-space: nowrap;
      vertical-align: middle;
      -ms-touch-action: manipulation;
      touch-action: manipulation;
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      background: none!important;
      color: inherit;
      color: #06C;
      border: none;
      padding: 0!important;
      font: inherit;
    }
    
    .like.active span {
      display: none;
    }
    
    .like.active:before {
      font-family: FontAwesome;
      content: "\f164";
      color: #009900;
    }
    
    .dislike.active span {
      display: none;
    }
    
    .dislike.active:before {
      font-family: FontAwesome;
      content: "\f165";
      color: #FF0000;
    }
    

    更新 js

    <?php
    // ...
    $sid = "18"; //session id
    $c_name = "12"; //article-post id
    $sel = "SELECT * FROM `likesordislikes` where `uid` = :sid AND `comid` = :comment";
    if (isset($_POST['likes'])) {
      $comid = mysqli_real_escape_string($con, $_POST['comid']);
      try {
        $stmt = $DB->prepare($sel);
        $stmt->bindValue(":sid", $sid);
        $stmt->bindValue(":comment", $comid);
        $stmt->execute();
        $fetch = $stmt->fetchAll();
        if (count($fetch) == 0) {
          $insert = "INSERT INTO `likesordislikes` (`vtype` , `uid` , `comid`) VALUES " . "( :like, :likerid , :comment)";
          $stmt = $DB->prepare($insert);
          $stmt->bindValue(":like", "1");
          $stmt->bindValue(":likerid", $sid);
          $stmt->bindValue(":comment", $comid);
          $stmt->execute();
        } elseif (count($fetch) > 0)  {
          if ($fetch[0]["vtype"] == "1") {
            $delete = "DELETE FROM `likesordislikes` where `uid` = :sid AND `comid` = :commnt";
            $stmt = $DB->prepare($delete);
            $stmt->bindValue(":sid", $sid);
            $stmt->bindValue(":commnt", $comid);
            $stmt->execute();
          } elseif ($fetch[0]["vtype"] == "0") {
            $sql = "UPDATE `likesordislikes` SET  `vtype` =  '1' WHERE `uid` = :id AND `comid` = :commn";
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":id", $sid);
            $stmt->bindValue(":commn", $comid);
            $stmt->execute();
          }
        }
      }
      catch (Exception $ex) {
        echo $ex->getMessage();
      }
    }
    if (isset($_POST['dislikes'])) {
      $comid = mysqli_real_escape_string($con, $_POST['comid']);
      try {
        $stmt = $DB->prepare($sel);
        $stmt->bindValue(":sid", $sid);
        $stmt->bindValue(":comment", $comid);
        $stmt->execute();
        $fetch = $stmt->fetchAll();
        if (count($fetch) == 0) {
          $insert = "INSERT INTO `likesordislikes` (`vtype` , `uid` , `comid`) VALUES " . "( :unlke, :likerid , :comment);";
          $stmt = $DB->prepare($insert);
          $stmt->bindValue(":unlke", "0");
          $stmt->bindValue(":likerid", $sid);
          $stmt->bindValue(":comment", $comid);
          $stmt->execute();
        } else {
          if ($fetch[0]["vtype"] == "0") {
            $delete = "DELETE FROM `likesordislikes` where uid = :sid AND comid = :commnt";
            $stmt = $DB->prepare($delete);
            $stmt->bindValue(":sid", $sid);
            $stmt->bindValue(":commnt", $comid);
            $stmt->execute();
          } elseif ($fetch[0]["vtype"] == "1") {
            $sql = "UPDATE `likesordislikes` SET `vtype` = '0' WHERE `uid` = :id AND comid = :commn";
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":id", $sid);
            $stmt->bindValue(":commn", $comid);
            $stmt->execute();
          }
        }
      }
      catch (Exception $ex) {
        echo $ex->getMessage();
      }
    }
    
    $slt = "SELECT" .
    " c.*," .
    " SUM(CASE WHEN lod.vtype=1 THEN 1 ELSE 0 END) likes," .
    " SUM(CASE WHEN lod.vtype=0 THEN 1 ELSE 0 END) dislikes" .
    " FROM" .
    " comments c LEFT JOIN likesordislikes lod ON lod.comid=c.id" .
    " WHERE" .
    " c.comname = '$c_name' AND c.media = '$type'" .
    " GROUP BY" .
    " c.id";
    $res = mysqli_query($con, $slt);
    
    while($fetc = mysqli_fetch_array($res)) {
      //$select3 = "SELECT c.* FROM comments c LEFT JOIN likesordislikes lod ON c.id=lod.comid WHERE `uid` = :sid"; (It was my question code)
      $select3 = "SELECT vtype FROM likesordislikes WHERE comid = :commentid AND `uid` = :sid LIMIT 1"; // its the solution i got in answer
      try {
        $stmtt = $DB->prepare($select3);
        $stmtt->bindValue(":commentid", $fetc['id']); //update from the answer
        $stmtt->bindValue(":sid", $sid);
        $stmtt->execute();
        $vfetch = $stmtt->fetchAll();
        if (count($vfetch) == 0) {
          $likeclass = "";
          $dislikeclass = "";
        } 
        elseif (count($vfetch) > 0) {
          if ($vfetch[0]["vtype"] == "1") {
            $likeclass = "active";
            $dislikeclass = "";
          } 
          elseif ($vfetch[0]["vtype"] == "0") {
            $likeclass = "";
            $dislikeclass = "active";
          }
        }
      }
      catch (Exception $ex) {
        echo $ex->getMessage();
      }
      ?>
      <div class="container1">
        <div class="div-right-mid">
          <span class="comment-text">
            <?php echo $fetc['usercom'] ?>  
          </span>
        </div>
        <div id="rating-votes">
          <button class="vbtn like <?php echo $likeclass; ?>" value="<?php echo $comid ?>">
            <span>
              <i class="fa fa-thumbs-o-up" aria-hidden="true">
              </i>
            </span>
          </button>
          <span class="likes">
            <font color="#6d7371">
              <?php echo $fetc['likes']; ?>
            </font>
          </span>&nbsp;
          <button class="vbtn dislike <?php echo $dislikeclass; ?>" value="<?php echo $comid ?>">
            <span>
              <i class="fa fa-thumbs-o-down" aria-hidden="true">
              </i>
            </span>
          </button>
          <span class="dislikes">
            <font color="#6d7371">
              <?php echo $fetc['dislikes']; ?>
            </font>
          </span>
        </div>
      </div>
      <?php
    }
    ?>
    

    这个PHP代码没有给我所需的结果。

    我正面临三个问题......

    1. 当用户翻阅评论时,拇指按钮未显示活动课(已解决)

    2. 只有第一个评论的拇指向上/拇指向下处理点击,第二个第三个,所有剩余评论的按钮无效点击(已解决)

    3. Ajax调用未向php发送数据(已编辑)

    4. CSS显示登录用户的任何特定评论的活动课程的翻阅/缩略按钮会发生什么

1 个答案:

答案 0 :(得分:0)

第一个问题

有几个问题:

  1. $select3查询没有带来likesordislikes表中的列(根据您的代码,您需要vtype列),它只会带来c.*} (这是comments表中的所有字段)。这可能是您必须使用try...catch的原因,因为它无法找到vtype索引。因此该代码行应更改为:

    $select3 = "SELECT c.*,lod.vtype FROM comments c LEFT JOIN likesordislikes lod ON c.id=lod.comid WHERE `uid` = :sid";
    
  2. $select3查询始终获取所有comments条记录,即使用户未与这些评论进行互动(因为您使用的是LEFT JOIN),然后每次都选择第一个(索引0)。由于您似乎并不真正使用表comments中的信息(不需要JOIN),理论上每个用户和评论应该有一条记录,我会将该行更改为:

    $select3 = "SELECT vtype FROM likesordislikes WHERE comid = :commentid AND `uid` = :sid LIMIT 1";
    

    然后,当然,绑定评论ID:

    $stmtt->bindValue(":commentid", $fetc['id']);
    
  3. 关于第二个问题

    您多次打印<div id="rating-votes">,这在HTML方面无效。 id属性在整个页面中应该是唯一的,如果你有两个,$('#id')之类的调用总会给你一个元素,第一个。因此,您应该将while中的HTML代码更改为使用class而不是id,如下所示:

    <!-- -->
    <div class="rating-votes">
      <button class="vbtn like <?php echo $likeclass; ?>" value="<?php echo $comid ?>" class="vote">
        <!-- -->
      </button>
      <!-- -->
      <button class="vbtn dislike <?php echo $dislikeclass; ?>" value="<?php echo $comid ?>" class="vote">
        <!-- -->
      </button>
      <!-- -->
    </div>
    <!-- -->
    

    然后,您应该更改您的Javascript调用,以便按class而不是id查找,如下所示:

    $('.rating-votes').likeDislike({    //.likeDislike function defined in like-dislike.js
      // ...
      click: function(value, l, d, event) {
        // ...
        var comid = $(this.element).find('.vote').val();
        // ...
      }
    });
    

    第三个问题

    数据未按预期到达,可能是因为您错过了&符号(&),即您拥有的代码:

    data: 'likes=' + likes + '&dislikes=' + dislikes + 'comid=' + comid,
    

    会转换为:

    data: 'likes=1&dislikes=2comid=3,
    

    所以你应该把它改成:

    data: 'likes=' + likes + '&dislikes=' + dislikes + '&comid=' + comid,
    

    虽然我建议你使用一个对象而不是自己连接这些值,但jQuery会为你处理所有奇怪的东西。为此,请将该行更改为:

    data:{
      likes:likes,
      dislikes:dislikes,
      comid:comid
    }
    
    • 更新

    你遇到的另一个问题是你发送的是对象,而不是对象的值,所以,而不是:

    data:{
      likes:likes,
      dislikes:dislikes,
      comid:comid
    }
    

    您应该:

    data:{
      likes:likes.val(),
      dislikes:dislikes.val(),
      comid:comid
    }
    
    • 更新

    前一个不是真正的问题,我的不好。你甚至不应该发送值,因为你只是在PHP中使用它们作为标志,所以你应该使用类似的东西:

    data:{
      likes:true,
      comid:comid
    }
    

    另一个问题是您的PHP代码同时接收likesdislikes(就像用户同时命中两者一样)。由于这不可能,我将PHP从if然后if更改为if然后else if,如下所示:

    if (isset($_POST['likes'])) {
      // ...
    }else if (isset($_POST['dislikes'])) {
      // ...
    }
    

    请记住,您仍在发送两个信号,因此这样您就可以始终执行第一个if。因此,您应该更改您的Javascript,以便它只发送两个信号之一。我真的不知道likeDislike是如何工作的,但你的代码看起来应该是这样的:

    // ...
    var data = {
      comid:comid
    };
    if(theUserLikesIt){
      data.likes = true;
    }else{
      data.dislikes = true;
    }
    $.ajax({
      // ...
      data: data,
      // ...
    });