Home Backend Development PHP Problem How to implement the add friend function in php

How to implement the add friend function in php

Apr 25, 2023 pm 06:19 PM

In recent years, social networks have become an indispensable part of people's daily lives. At the same time, friend relationships, as an important part of social networks, have also received more and more attention in their implementation. This article will introduce how to use PHP to implement the function of adding friends.

1. Database design

In the process of implementing the friend adding function, a friend relationship table needs to be designed. The table should contain at least the following fields:

  1. friend_id: the unique ID of the friend relationship table
  2. user_id1: the user ID of the friend relationship party 1
  3. user_id2: the friend relationship Party 2's user ID
  4. status: Friend relationship status. Optional values ​​include "1" (already a friend), "0" (pending), and "-1" (rejected).

2. Add friends

When adding friends in PHP, you need to go through the following steps:

  1. Verify whether the ID entered by the user exists in In the database;
  2. Check whether the friend to be added is already the user's friend;
  3. If there is no friend relationship between the two users, add a new friend relationship record with the status of " 0" (pending);
  4. If the two users are already friends, no operation will be performed.

The following is a simple PHP code example to implement the function of adding friends:

<?php
// 连接数据库
$con = mysqli_connect("localhost","root","mypassword","mydatabase");

// 获取用户输入
$user_id1 = $_POST[&#39;user_id1&#39;];
$user_id2 = $_POST[&#39;user_id2&#39;];

// 验证用户输入是否合法
if(!is_numeric($user_id1) || !is_numeric($user_id2)) {
    echo "Error: 用户ID必须为数字";
    exit();
}

// 检查要添加的好友是否已经是用户的好友
$sql = "SELECT * FROM friend_relation WHERE ((user_id1 = $user_id1 AND user_id2 = $user_id2) OR (user_id2 = $user_id1 AND user_id1 = $user_id2)) AND status = 1";
$result = mysqli_query($con,$sql);

if(mysqli_num_rows($result) > 0) {
    echo "该用户已经是您的好友!";
    exit();
}

// 如果两个用户之间没有好友关系,则添加一条新的好友关系记录,其中状态为“0”(待处理)
$sql = "INSERT INTO friend_relation (user_id1,user_id2,status) VALUES ($user_id1,$user_id2,0)";
if(mysqli_query($con,$sql)) {
    echo "添加好友请求已经发送!";
} else {
    echo "Error: " . mysqli_error($con);
}

mysqli_close($con);
?>
Copy after login

In the above code, we use the mysqli extension to connect to the MySQL database and pass The POST method obtains the IDs of the two users, and then performs input verification and friend relationship checking. If the friend to be added is already a friend of the user, a prompt message is output; if there is no friend relationship between the two users, a new friend relationship record is added to the database, and a success prompt message is output.

3. Friend request processing

In the friend adding function, it is also necessary to implement the processing of friend requests. When a user sends a friend request to another user, the requested user needs to perform corresponding processing, including accepting or rejecting the request.

In the database design, we set the friend relationship status (status) to "0" to indicate that the friend request has not been processed, to "1" to indicate that the friend is already a friend, and to "-1" to indicate that the friend is The request has been denied. Therefore, in the friend request processing function, we need to add the corresponding status update code.

The following is a simple PHP code example for processing friend requests:

<?php
// 连接数据库
$con = mysqli_connect("localhost","root","mypassword","mydatabase");

// 获取用户输入
$user_id1 = $_POST[&#39;user_id1&#39;];
$user_id2 = $_POST[&#39;user_id2&#39;];
$action = $_POST[&#39;action&#39;]; // 操作类型,可选值包括“accept”和“reject”

// 验证用户输入是否合法
if(!is_numeric($user_id1) || !is_numeric($user_id2)) {
    echo "Error: 用户ID必须为数字";
    exit();
}

// 更新好友关系状态
if($action == "accept") {
    $sql = "UPDATE friend_relation SET status = 1 WHERE user_id1 = $user_id1 AND user_id2 = $user_id2";
    if(mysqli_query($con,$sql)) {
        echo "您已经同意该好友请求!";
    } else {
        echo "Error: " . mysqli_error($con);
    }
} else if($action == "reject") {
    $sql = "UPDATE friend_relation SET status = -1 WHERE user_id1 = $user_id1 AND user_id2 = $user_id2";
    if(mysqli_query($con,$sql)) {
        echo "您已经拒绝了该好友请求!";
    } else {
        echo "Error: " . mysqli_error($con);
    }
} else {
    echo "Error: 请输入正确的操作类型!";
}

mysqli_close($con);
?>
Copy after login

In the above code, we obtained the IDs and operation types of two users through the POST method, "Accept" means accepting the friend request, and "reject" means rejecting the friend request. Then, we updated the friend relationship status through the UPDATE statement and output the corresponding prompt information.

Through the above PHP code example, we can easily implement the functions of adding friends and processing friend requests. In actual development, it can be appropriately modified according to specific needs and optimized in terms of security and performance.

The above is the detailed content of How to implement the add friend function in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles