gpt4 book ai didi

PHP Like/Unlike 按钮与 jquery

转载 作者:行者123 更新时间:2023-12-01 04:39:14 25 4
gpt4 key购买 nike

我正在按照 youtube 上的教程为我的状态系统制作一个简单的喜欢/不喜欢按钮,我完成了大部分工作,但它不会更新我的喜欢,也不会将喜欢插入数据库,请帮我说怎么了,我已经尝试了很多了..

获取状态的函数:

 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();


}

最佳答案

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();


}

关于PHP Like/Unlike 按钮与 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com