我想在我的网站上制作一个按钮,这样用户就可以在某个游戏上点击关注或取消允许。
这是我的下表:跟随按钮表
当用户点击与游戏ID相关联的按钮时,它应该在该ID的game_follow数据库中插入1。
(我已经有了一个游戏和用户表,我知道如何获得每个ID)
我知道这是一个宽泛的问题,但也许有人可以给我指明正确的方向,或者给我看另一个教程。
编辑:到目前为止,这还不起作用:
这是我的按钮:
<button class="follow-game" data-game_id="<?php echo $game_id['id']; ?>">Follow!</button>
这是我的ajax调用:
$(function(){
$('.follow-game').click(function(){
follow_game(this);
});
});
function follow_game(obj){
var game_id = $(obj).attr('data-game_id');
jQuery.ajax({
url: 'follow.php',
type: 'POST',
data: { game_id : game_id },
success: function(data) {
alert("You Followed!");
},
error: function () {
alert("Something went wrong with Follow Button.");
}
});
}
这是我的关注。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);
我的表是上方的图像链接
这绝对是一个宽泛的问题,所以,宽泛的答案:
我的建议是在按钮上附加一个javascript监听器,它将调用一个运行php脚本的ajax函数,执行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。当然,这根本没有考虑到安全性等,但一旦基本功能关闭,请担心这一点。