开发者

PHP+Ajax : Add-a-friend system

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 开发者_StackOverflow中文版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?


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:

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;

A full example script can be found here : http://pastie.org/1242699

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜