2
我試圖在我的頁面上實現一個喜歡/不喜歡的按鈕。我設法讓這個按鈕起作用(當它被點擊時,它會變成不喜歡的,反之亦然),它也會在數據庫表上創建或刪除。現在的問題是喜歡的反面。它僅在第一次點擊按鈕時起作用,即如果最初有2 likes
,我不喜歡帖子顯示1 likes
,但是如果我嘗試再次點擊它,它會一直顯示1 like
,我必須重新加載頁面才能看到它更改爲2 likes
。PHP喜歡/不喜歡按鈕只能第一次工作
這是我到目前爲止有:
JQUERY
$(document).on('click', ".miPiace", function() {
trova = '';
commentoORisposta = '';
valCOR = '';
var comOrisp;
try{
trova = $(this).parentsUntil("#fermamiQui");
commentoORisposta = trova.find(".idCommento");
comOrisp = 'commento';
valCOR = commentoORisposta.val();
} catch(err){
trova = $(this).parentsUntil(".infoCommento");
commentoORisposta = trova.find(".idRisposta");
comOrisp = 'risposta';
valCOR = commentoORisposta.val();
}
valCOR = commentoORisposta.val();
if ($(this).hasClass('fa-thumbs-o-up')) {
$(this).removeClass('fa-thumbs-o-up');
$(this).addClass('fa-thumbs-up');
$.get("lib/ottieniCose.php", { like: "", id: valCOR, comOrisp: comOrisp })
.done(function(data) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
}else if($(this).hasClass('fa-thumbs-up')){
$(this).removeClass('fa-thumbs-up');
$(this).addClass('fa-thumbs-o-up');
$.get("lib/ottieniCose.php", { remLike: "", id: valCOR, comOrisp: comOrisp })
.done(function(data) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
};
});
PHP
if (isset($_GET['like'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->set_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->set_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
} elseif (isset($_GET['remLike'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->remove_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->remove_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
}
其他PHP文件那裏是$建議與類
public function get_likes($id, $commento){
$idComm = 0;
$idRisp = 0;
$retVal = ($commento) ? $idComm = $id : $idRisp = $id;
if ($idComm != 0){
$query = "SELECT commento,
(SELECT COUNT(*) FROM likes
WHERE commento = {$idComm})
AS like_count FROM likes";
} elseif($idRisp != 0){
$query = "SELECT risposta,
(SELECT COUNT(*) FROM likes
WHERE risposta = {$idRisp})
AS like_count FROM likes";
}
$trovaQuanti = mysqli_query($_SESSION['connessione'], $query);
$trovaDavveroQuanti = mysqli_fetch_assoc($trovaQuanti);
if ($trovaDavveroQuanti == null) {
return '0';
}
return $trovaDavveroQuanti['like_count'];
}
** WARNING **:當使用'mysqli'你應該使用參數化查詢,而['bind_param'(http://php.net/manual/en/mysqli-stmt.bind-param。 PHP)將用戶數據添加到您的查詢。 **不要**使用字符串插值或連接來完成此操作,因爲您將創建嚴重的[SQL注入漏洞](http://bobby-tables.com/)。 **絕不**將'$ _POST'數據直接放入查詢中。 – tadman