members.php

Using Example 21-9, members.php, your users will be able to find other members and choose to add them as friends (or drop them if they are already friends). This program has two modes. The first shows a user’s profile, and the second lists all members and their relationships to you.

Viewing a User’s Profile

In the first mode a test is made for the GET variable 'view'. If it exists, a user wants to view someone’s profile; the program does that using the showProfile function, along with providing a couple of links to the user’s friends and messages.

Adding and Dropping Friends

After that the two GET variables, 'add' and 'remove', are tested. If one or the other has a value, it will be the username of a user to either add or drop as a friend. This is achieved by looking up the user in the MySQL friends table and either inserting a friend’s username or removing it from the table.

Of course, every posted variable is first passed through sanitizeString to ensure it is safe to use with MySQL.

Listing All Members

The final section of code issues a SQL query to list all usernames. The code places the number returned in the variable $num before outputting the page heading.

A for loop then iterates through each and every member, fetching their details and then looking them up in the friends table to see if they are either being followed by or are a follower of the user. Anyone who is both a follower and a followee is classed as a mutual friend.

The variable $t1 is nonzero when ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.