PHP+Ajax : Add-a-friend system

标签 php mysql ajax mysqli friend

我正在尝试制作一个用于添加 friend 的小项目。 当您单击“添加好友”按钮时,您将使用好友 id 和用户名(它们是每个添加按钮的 id 和 name 属性)向 add.php 文件发送 Ajax 调用。 (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");
      }
   });
});

问题: 当我点击“添加 friend ”时,它确实会提醒“成功”,但每次只有一张表得到更新,甚至根本没有表。 虽然有一次我点击了它并且它确实起作用了(那次我没有更改代码,我尝试每 20 秒点击一次)。

我该如何解决这个问题?

最佳答案

如果我理解正确的话,你似乎正在为每个用户的 friend 创建一个新表(1个用户表+ X个名为用户名的表),这不是一个好方法,你最好只使用2个表:users和 user_friends 如下:

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null
)
engine=innodb;

drop table if exists user_friends;
create table user_friends
(
user_id int unsigned not null,
friend_user_id int unsigned not null,
created_date datetime not null,
primary key (user_id, friend_user_id) -- note clustered composite PK (innodb only)
)
engine=innodb;

完整的示例脚本可以在这里找到:http://pastie.org/1242699

希望这有帮助。

关于PHP+Ajax : Add-a-friend system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003362/

相关文章:

php - jcarousel 不滚动图像

php - 翻译 CodeIgniter 的表单验证错误消息

php - 当有人发布内容时,Facebook 如何更新内容

php - 如何使用 Laravel Eloquent 返回多个关系?

PHP/MySQL - MySQL 查询对每个特定列的结果进行排序

php - 使用 XAMPP 访问 Laravel Homestead 中的 phpMyAdmin

mysql - 如果百分比高于特定值,则连接表

php - Codeigniter form_validation 总是返回 false

javascript - 多文件上传验证javascript if语句不起作用

http - PUT、DELETE、HEAD 等方法在大多数 Web 浏览器中都可用吗?