PHP喜欢/不同于带有jquery的按钮

时间:2017-03-02 02:46:40

标签: php jquery

我正在关注youtube上的一个教程,为我的状态系统制作一个简单的Like /不同按钮,我完成了大部分工作,但它不会更新我的喜欢而不会将其插入到数据库中,请帮我说什么不对,我现在尝试了很多..

获取状态的功能:

 function getStatus($conn) {
       $sql = "SELECT * FROM status ORDER BY sid DESC";
       $query = mysqli_query($conn, $sql);
       while ($row = $query->fetch_assoc()) {
           echo "<div class='post'>".$row['message']."<br>";

                $result = mysqli_query($conn, "SELECT * FROM status_like WHERE uid=1 and sid=".$row['sid']."");
                if (mysqli_num_rows($result) == 1) {
                    echo "<span><a href='' class='unlike' id='".$row['sid']."'>unlike</a></span>";
                } else {
                    echo "<span><a href='' class='like' id='".$row['sid']."'>like</a></span></div>";
                }
                }


       }

jquery代码

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
          <script type="text/javascript">
            $(document).ready(function(){
                $('.like').click(function(){
                    var sid = $(this).attr('id');
                    $.ajax({
                        url: 'test.php',
                        type: 'post',
                        async: false,
                        data: {
                            'liked': 1,
                            'sid': sid

                        },
                        success:function(){

                        }
                    });
                });
            });
          </script>

以及我认为问题出现的最后一个PHP代码:

if (isset($_POST['liked'])) {
        $sid = $_POST['sid'];
        $sql = "SELECT * FROM status WHERE sid=$sid";
        $query = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($query);
        $n = $row['likes'];
        $uid = 1;

        $sql2 = "UPDATE status SET likes=$n+1 WHERE sid=$sid";
        $sql3 = "INSERT INTO status_like (uid, sid, username) VALUES (1, '$sid', '$uid')";
        mysqli_query($conn, $sql2);
        mysqli_query($conn, $sql3);
        exit();


    }

1 个答案:

答案 0 :(得分:1)

if (isset($_POST['liked'])) {
        $sid = $_POST['sid'];
        $sql = "SELECT * FROM status WHERE sid=$sid";
        $query = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($query);
        //$n = $row['likes']; // your code            
        $n = (int) $row['likes']; // try like this.. might be likes in string so convert to int
        $uid = 1;

        //$sql2 = "UPDATE status SET likes=$n+1 WHERE sid=$sid"; // Your code

        // Do like this `status` in query because status is reserved keyword of MySql for more details you could visit this link https://dev.mysql.com/doc/refman/5.7/en/keywords.html
        $sql2 = "UPDATE `status` SET likes=$n+1 WHERE sid=$sid";
        $sql3 = "INSERT INTO status_like (uid, sid, username) VALUES (1, '$sid', '$uid')";
        mysqli_query($conn, $sql2);
        mysqli_query($conn, $sql3);
        exit();


    }