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

brqmpdu1  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(164)

我想有喜欢我的博客文章,它应该这样工作:用户将点击的东西,它增加了+1的数字,并存储在数据库中,我有一个名为post\ u喜欢在我的数据库列。但是在从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>
euoag5mw

euoag5mw1#

您可以从javascript传递post id并在后端更新like。考虑以下示例:

$("#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');
    }

希望这有帮助。

相关问题