2015-11-03 50 views
1

我想在我的網站上製作一個按鈕,以便用戶可以在某個遊戲上點擊關注或取消關注。如何在我的網站上添加Follow - UnFollow按鈕?

這裏是我的表如下: Follow Button Table

當用戶點擊與遊戲ID相關聯的按鈕,它應該插入1到該ID的game_follow數據庫。

(我已經有一個遊戲和用戶表,我知道如何讓每個那些ID的的)

我知道這是一個很寬泛的問題,但也許有人可以點我在正確的方向,或顯示我另一個教程。

編輯: 這個至今無法正常工作:

我的繼承人按鈕:

<button class="follow-game" data-game_id="<?php echo $game_id['id']; ?>">Follow!</button>

繼承人我Ajax調用:

$(function(){ 
 
\t \t $('.follow-game').click(function(){ 
 
\t \t \t follow_game(this); 
 
\t \t }); 
 
\t }); 
 

 
\t function follow_game(obj){ 
 
\t \t var game_id = $(obj).attr('data-game_id'); 
 

 
\t \t jQuery.ajax({ 
 
\t \t \t url: 'follow.php', 
 
\t \t \t type: 'POST', 
 
\t \t \t data: { game_id : game_id }, 
 
\t \t \t success: function(data) { 
 
\t \t \t \t alert("You Followed!"); 
 
\t \t \t }, 
 
\t \t \t error: function() { 
 
\t \t \t \t alert("Something went wrong with Follow Button."); 
 
\t \t \t } 
 
\t \t }); 
 

 
\t }

這裏是我的follow.php

<?php 
 

 
    require_once 'core/init.php'; 
 

 
    // Set user_id to the currently logged in user. 
 
    $user_id = $user_data['id']; 
 

 
    // Set $game_id to the current ID of the game (coming from ajax call) 
 
    $game_id = $_POST['game_id']; 
 

 
    // Grab the game (ID) from the games table, then Query it. 
 
    //$SQL_SELECT_GAME = "select * from games where id = '$game_id'"; 
 
    //$db->query($SQL_SELECT_GAME); 
 

 
    // Do an update on game_follow table, and set follow = 1 (means that this game is being followed) where the user_id = $user_id and game_id = $game_id, then Query it. 
 
    $SQL_UPDATE = "update game_follows set follow = 1 where user_id = '$user_id' and game_id = '$game_id'"; 
 
    $db->query($SQL_UPDATE);

我的表是上面

回答

1

絕對是一個寬泛的問題的圖片鏈接,因此,廣泛的答案:

我的建議是將一個JavaScript監聽器附加到按鈕上,該按鈕將調用ajax函數ru nning一個php腳本,執行mysql查詢來相應地更新你的數據庫。

對於HTML:

<button class="follow-game" data-game_id="1">Follow!</button 

對於JavaScript的:(jQuery是我的偏好,所以這是我的例子)

$(function(){ 
    $('.follow-game').click(function(){ 
     follow_game(this); 
    }); 
}); 
function follow_game(obj){ 
game_id = $(obj).attr('data-game_id'); 

$.ajax({ 
    url: '/follow.php', 
    type: 'POST', 
    dataType: 'json', 
    data: { 
    game_id : game_id 
    }, 
    success: function(rs){ 
    alert("yay"); 
    } 
}); 

} 

對於PHP/MySQL的:

$user_id = $_SESSION['user_id']; 
$game_id = $_POST['game_id']; 
$sql = "UPDATE `game_follows` SET follow = 1 WHERE user_id='{$user_id}' AND $game_id='{$game_id}'"; 

然後用你正在使用的任何mysql連接/方法運行sql。 當然,這根本不考慮安全性等問題,但是一旦你的基本功能下降,就擔心這一點。

+0

當你寫數據game_id = 1,這是否意味着你想讓我得到game_id如:data-game_id =「<?php echo $ game ['id'];?>」 – David

+0

是的,這就是我會推薦。有很多方法可以做到,但我覺得這是最簡單的方法。 –

相關問題