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