评估PHP和MySQL中的特定注释

时间:2016-06-04 19:17:19

标签: javascript php jquery html mysql

所以我有一个系统来发布评论到一个页面,它们都是从数据库调用并显示在页面上。每个评论都有一个名为“评级”的值,默认为1,每个评论在其左侧有向上和向下箭头,用于评级和评级,这将分别增加和降低评级。现在,我已经想出了如何增加和减少数字,但是我的方式,所有帖子的评分同时增加,无论我评价哪个帖子。

这是我的“加价”功能:

$(function () {
        $('#rateup').click(function() {
            var request = $.ajax( {
                type: "POST",
                url: "rateup.php"                               
            });
            request.done(function( msg ) {
                return;
                });
            request.fail(function(jqXHR, textStatus) {

            });
            location.reload();
        });
    });

这是我的rateup.php文件:

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";

// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1)");

mysqli_close($connection);

echo 'OK';   
?>

我知道它增加所有帖子评级的原因是因为我没有指定要增加的帖子,而这正是我需要帮助的。当点击所述帖子左侧的链接时,如何指定评分哪个帖子?

链接如下所示:

echo " <a class='noStyle' id='rateup' href='index.php'>&#9660;</a>";

这只是一个与帖子相呼应的unicode向上箭头。

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要指定要点击的链接并通过表单发送。 您可以在链接中添加data- *标记来执行此操作:

echo " <a class='noStyle' id='rateup' href='index.php' data-id='".$commentID."'>&#9660;</a>";

然后,您可以在提交表单并将其作为数据发送时获取该值:

$(function () {
    $('.rateup').click(function() {
        var id = $(this).data('id');
        $.ajax( {
            type: "POST",
            data: "id=" + id,
            url: "rateup.php"                               
        });
        location.reload();
    });
});

然后您可以通过以下表单检索:

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";

// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];

// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1) WHERE commentID = '".$id."'");

mysqli_close($connection);

echo 'OK';   
?>