使用jquery使用$ .post更新mysql时出错

时间:2018-06-14 06:06:54

标签: php jquery mysql ajax

我想要我的博客文章,它应该像这样工作:用户将点击某些内容并将该数字增加+1并将其存储在数据库中,我的数据库中有一个名为post_like的列。但是在增加0到1之后(当我尝试从1增加到2或更多时)我得到错误。 jquery的:

 $("#insert_like").click(function(e){
        alert('s')
        var like = $("#insert_like").val();
        like += 1;
        var post_id = $("#post_id").val();
        $.post("./inc/like.php", {
            like: like,
            post_id: post_id
        }, function(data, status){
            $("#insert_like").text(data);
            like = 0;
        });
    });

PHP:

<?php
if (isset($_POST['like'])) {
    require_once 'db.inc.php';
    $like = $_POST['like'];
    $post_id = $_POST['post_id'];




    $q = "UPDATE posts set post_like = ? WHERE post_id=? LIMIT 1";
    $stmt = $conn->prepare($q);
    $stmt->bind_param('ii', $like, $post_id);
    $stmt->execute();
    if ($stmt->affected_rows == 1) {
        echo "$like";
    } else {
        echo "error: $stmt->error";
    }
    $stmt->close();
    $conn->close();
} else {
    header('Location: ../home.php');
}

HTML:

<p>Post like: <span id="insert_like" style="cursor: pointer"><?php echo $post_like ?></span> </p>

1 个答案:

答案 0 :(得分:1)

您可以从javascript传递Post Id并在后端更新喜欢的内容。请考虑以下示例:

$("#insert_like").click(function(e){
    $.post("./inc/like.php", {
        post_id: $("#post_id").val()
    }, function(data, status){
        $("#insert_like").text(data);
        like = 0;
    });
});

并在后端

<?php
    if (isset($_POST['like'])) {
        require_once 'db.inc.php';
        $post_id = $_POST['post_id'];

        $q = "UPDATE posts SET post_like = (post_like + 1) WHERE post_id = ?";
        $stmt = $conn->prepare($q);
        $stmt->bind_param('i', $post_id);
        $stmt->execute();
        if ($stmt->affected_rows == 1) {
           // get the updated likes and return as response.
        } else {
           echo "error: $stmt->error";
        }
        $stmt->close();
        $conn->close();
    } else {
        header('Location: ../home.php');
    }

希望这有帮助。