Add friends, database design and implementation

Source: Internet
Author: User

Database design:



CREATE table user (id int auto_increment,name varchar (),key (ID));
Relationship table: CREATE TABLE friendrelation (id int key auto_increment,id_left Int (5 ),id_right Int (5));

Database Information Display:

Note: When inserting a database, ensure data, left Id_left < Id_right, this way to prevent data redundancy,

If, if not, add a friend to insert two data into the database

Query your friend's PHP code:

Query thinking Analysis: Find Id_left = ID to check, take the results out, then find id_right = ID to look for, and then combine the results two times, that is, the ID of all friends ....

<?PHP//Conncet to Database$mysqli=NewMysqli (' 127.0.0.1 ', ' root ', ' root ', ' friends ') or die(' Can not connect to Mysqli '); Use your own message$sql= ' Select Id_right from friendrelation where id_left=5 ';    Each query executes two queries, this is the first step; $result=$mysqli->query ($sql); $res=Array(); foreach($result  as $v){        $res[]=$v; }    $sql 2= ' Select Id_left from friendrelation where id_right=5 ';//This is the second step of the query, and then two times the structure of the query to join together; $result 2=$mysqli->query ($sql 2); foreach($result 2  as $v){        $res[]=$v; }    foreach($res  as $v){        foreach($v  as $key=$value) {            $sql 3= "SELECT name from user where id=$value"; $result 3=$mysqli->query ($sql 3); foreach($result 3  as $key=$value) {                Echo"Name is:".$value[' name ']. " \ n "; }         }             }

Add friends, database design and implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.