2015-11-03 160 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

是的,这就是我会推荐。有很多方法可以做到,但我觉得这是最简单的方法。 –

相关问题