开发者

Add friends function in PHP

开发者 https://www.devze.com 2023-03-28 13:58 出处:网络
I would like to make it able for my users to add each other as friends. I just don\'t know exactly how to do it. 开发者_开发知识库

I would like to make it able for my users to add each other as friends. I just don't know exactly how to do it.

开发者_开发知识库

I have a table called "members" where the users have (ofc) and ID,username,pass etc etc. and then I was thinking of creating another table called "friends", where I was planning to have the rows -> username (the friend added) and friend_to (who the friend 'belongs' to).

But; I just don't know - how I should make the "add friend" link, and make it INSERT INTO the table? Can I make an onClick on the link, or what should I do? :-s

Thanks in advance.


Have a table called friends have rows, (id, user_id, friend_id, status, time)

id is the index, user_id is the one requesting friendship, friend_id is the receiver, status is the status of friendship like pending or declined, and time is the timestamp of the time when the request was sent.

Then in a php code check if the users aren't friends then let them add each other as friends. One way you could check was like this

(SELECT COUNT(*) AS total WHERE (`user_id` = ".$_SESSION['user_id']." AND `friend_id` = ".$_GET['friend_id'].") OR (`user_id` = ".$_GET['friend_id']." AND `friend_id` = ".$_SESSION['user_id']."))

the above code will check if they are users, and if they are you would not let them re add each other, if they aren't the user gets a button to add them to friends, where it inserts into a database new row, with user_id being the user sending and friend_id the user's page the sender is submitting the button from


On the backend, you will need separate PHP functionality (easiest way is to simply have a separate PHP page) to handle the result of the "add friend" link. Your table layout seems adequate from what you have describe. The "Add Friend" link will need to send a request back to the add_friend PHP handler which includes ID of the user and the ID of the user they added. And this handler will be where you include the MySQL code for performing the insert, based on the data that is provided to it.

On the front end, you can have the link send them to a new page, or you can use an onclick event to issue an AJAX request and update things behind the scenes without requiring a page reload. That choice is up to you and what fits your design best. The later is more complicated and will require some Javascript and/or jQuery to handle the AJAX parts, but it often results in a more pleasant user experience.

0

精彩评论

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

关注公众号