PHP+Ajax:添加好友系统
我正在尝试制作一个添加朋友的小项目。 当您单击“添加好友”按钮时,您将发送带有好友 ID 和信息的 Ajax 调用。 username(它们是每个添加按钮的 id 和 name 属性)添加到 add.php 文件中。 (mysql结构是:1个users表+X个以用户名命名的表(列:friendid,ispending)) 在 PHP 文件中只有 2 个 MySQLi 查询: 这是添加文件的代码:
session_start();
$friendid = $_POST['id'];
$myname = $_SESSION['username'];
$friendname = $_POST['name'];
$myid = $_SESSION['id'];
$add = new Mysqlconnect();
$add->db->query("INSERT INTO $myname VALUES($friendid, 'yes')");
$add->db->query("INSERT INTO $friendname VALUES ($myid, 'yes')");
$add->db_Close();
需要 Mysqlconnect 类 我只是不希望这里的代码太长。 这是 Ajax 调用:
$('.add').click(function(){
var name = $(this).attr("name");
var id = $(this).attr("id");
$.ajax({
type: "POST",
data: "&name="+name+"&id="+id,
url: 'add.php',
success: function(){
alert("success");
}
});
});
问题: 当我单击“添加朋友”时,它确实会提醒“成功”,但每次只有一张表得到更新,甚至根本没有表。 虽然有一次我点击了它并且它确实起作用了(那次我没有更改代码,我尝试每 20 秒点击一次)。
我该如何解决这个问题?
I'm trying to make a little project for adding friends.
When you click the add friend button you are sending an Ajax call with the friend id & username (they are the id and name attributes of each add button) to the add.php file.
(The mysql structure is: 1 users table + X tables named the user's name(columns: friendid, ispending))
In the PHP file there are only 2 MySQLi queries: Here is the code for the add file:
session_start();
$friendid = $_POST['id'];
$myname = $_SESSION['username'];
$friendname = $_POST['name'];
$myid = $_SESSION['id'];
$add = new Mysqlconnect();
$add->db->query("INSERT INTO $myname VALUES($friendid, 'yes')");
$add->db->query("INSERT INTO $friendname VALUES ($myid, 'yes')");
$add->db_Close();
The Mysqlconnect class is required i just didn't want the code here to be too long.
Here's the Ajax call:
$('.add').click(function(){
var name = $(this).attr("name");
var id = $(this).attr("id");
$.ajax({
type: "POST",
data: "&name="+name+"&id="+id,
url: 'add.php',
success: function(){
alert("success");
}
});
});
THE PROBLEM :
When I click "add friend" it does alert "success" but only one table gets updated everytime or even no table at all.
Though one time I clicked it and it did work (I did not change the code that time, I tried clicking like every 20 seconds).
How can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,你似乎正在为每个用户的朋友创建一个新表(1个用户表+ X个名为用户名的表),这不是一个好方法,你最好只使用2个表:users和user_friends如下:
可以在此处找到完整的示例脚本:http://pastie.org/1242699
希望这会有所帮助。
if i understood you correctly you seem to be creating a new table for each user's friends (1 users table + X tables named the user's name) this isnt a good approach and you'd be better off with just 2 tables: users and user_friends as follows:
A full example script can be found here : http://pastie.org/1242699
Hope this helps.