This post is for my social network course and is assuming you have reached the relevant section. If you haven’t yet enrolled in the course, click here
So one feature that hasn’t been implemented until now is the ability to cancel friend requests. For example, if I accidentally send someone a friend request, I have no way of cancelling it. This is actually really easy to fix and essentially all we need to do when they click the cancel request button is remove the request from the ‘friend_requests’ table.
Open profile.php and find the line of code which outputs our ‘Request Sent’ button. It should look like this:
else if ($logged_in_user_obj->didSendRequest($username)) {
echo '<input type="submit" name="" class="default" value="Request Sent">';
}
Give the name attribute a value such as name=”cancel_request”. We need this name attribute so that we can handle the button press.
else if ($logged_in_user_obj->didSendRequest($username)) {
echo '<input type="submit" name="cancel_request" class="default" value="Request Sent">';
}
Next, add the handler for the button at the top of profile.php (underneath all the other handlers):
if(isset($_POST['remove_friend'])) {
$user = new User($con, $userLoggedIn);
$user->removeFriend($username);
}
if(isset($_POST['add_friend'])) {
$user = new User($con, $userLoggedIn);
$user->sendRequest($username);
}
if(isset($_POST['respond_request'])) {
header("Location: requests.php");
}
if(isset($_POST['cancel_request'])) {
$user = new User($con, $userLoggedIn);
$user->cancelRequest($username);
}
What this does, is when the cancel_request button is pressed, it creates an instance of the user object and then calls the ‘cancelRequest’ function (which we haven’t created yet). This function will take a parameter which is the username of the person that you sent the request to (AKA the username of the profile you are currently on). Scroll to the top of profile.php and you will see us create this $username variable.
And finally, add the cancelRequest function to the User.php class:
public function cancelRequest($user_to) {
$user_from = $this->user['username'];
mysqli_query($this->con, "DELETE FROM friend_requests WHERE user_to='$user_to' AND user_from='$user_from'");
}
All this function does is delete from the requests table where the user the request was sent to is the profile user (which we passed into the function) and the person who sent the request is us.
That’s it! That’s all there is too it! 🙂
Reece