Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

Friend Lists and Social Network Notifications Tutorial

In this tutorial you can learn PHP, MySQL, JavaScript and Ajax programming logic behind scripting friend lists and notification lists within your custom built social networking website system. We also cover accepting and rejecting friend requests, that portion gets placed into our friend_system.php module that can be called by Ajax anywhere in your website software. friend_system.php <?php include_once("../php_includes/check_login_status.php"); if($user_ok != true || $log_username == "") { exit(); } ?><?php if (isset($_POST['type']) && isset($_POST['user'])){ $user = preg_replace('#[^a-z0-9]#i', '', $_POST['user']); $sql = "SELECT COUNT(id) FROM users WHERE username='$user' AND activated='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $exist_count = mysqli_fetch_row($query); if($exist_count[0] < 1){ mysqli_close($db_conx); echo "$user does not exist."; exit(); } if($_POST['type'] == "friend"){ $sql = "SELECT COUNT(id) FROM friends WHERE user1='$user' AND accepted='1' OR user2='$user' AND accepted='1'"; $query = mysqli_query($db_conx, $sql); $friend_count = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$user' AND blockee='$log_username' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $blockcount1 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$log_username' AND blockee='$user' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $blockcount2 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$log_username' AND user2='$user' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count1 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$user' AND user2='$log_username' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count2 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$log_username' AND user2='$user' AND accepted='0' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count3 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$user' AND user2='$log_username' AND accepted='0' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count4 = mysqli_fetch_row($query); if($friend_count[0] > 99){ mysqli_close($db_conx); echo "$user currently has the maximum number of friends, and cannot accept more."; exit(); } else if($blockcount1[0] > 0){ mysqli_close($db_conx); echo "$user has you blocked, we cannot proceed."; exit(); } else if($blockcount2[0] > 0){ mysqli_close($db_conx); echo "You must first unblock $user in order to friend with them."; exit(); } else if ($row_count1[0] > 0 || $row_count2[0] > 0) { mysqli_close($db_conx); echo "You are already friends with $user."; exit(); } else if ($row_count3[0] > 0) { mysqli_close($db_conx); echo "You have a pending friend request already sent to $user."; exit(); } else if ($row_count4[0] > 0) { mysqli_close($db_conx); echo "$user has requested to friend with you first. Check your friend requests."; exit(); } else { $sql = "INSERT INTO friends(user1, user2, datemade) VALUES('$log_username','$user',now())"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); echo "friend_request_sent"; exit(); } } else if($_POST['type'] == "unfriend"){ $sql = "SELECT COUNT(id) FROM friends WHERE user1='$log_username' AND user2='$user' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count1 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$user' AND user2='$log_username' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count2 = mysqli_fetch_row($query); if ($row_count1[0] > 0) { $sql = "DELETE FROM friends WHERE user1='$log_username' AND user2='$user' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); echo "unfriend_ok"; exit(); } else if ($row_count2[0] > 0) { $sql = "DELETE FROM friends WHERE user1='$user' AND user2='$log_username' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); echo "unfriend_ok"; exit(); } else { mysqli_close($db_conx); echo "No friendship could be found between your account and $user, therefore we cannot unfriend you."; exit(); } } } ?><?php if (isset($_POST['action']) && isset($_POST['reqid']) && isset($_POST['user1'])){ $reqid = preg_replace('#[^0-9]#', '', $_POST['reqid']); $user = preg_replace('#[^a-z0-9]#i', '', $_POST['user1']); $sql = "SELECT COUNT(id) FROM users WHERE username='$user' AND activated='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $exist_count = mysqli_fetch_row($query); if($exist_count[0] < 1){ mysqli_close($db_conx); echo "$user does not exist."; exit(); } if($_POST['action'] == "accept"){ $sql = "SELECT COUNT(id) FROM friends WHERE user1='$log_username' AND user2='$user' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count1 = mysqli_fetch_row($query); $sql = "SELECT COUNT(id) FROM friends WHERE user1='$user' AND user2='$log_username' AND accepted='1' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $row_count2 = mysqli_fetch_row($query); if ($row_count1[0] > 0 || $row_count2[0] > 0) { mysqli_close($db_conx); echo "You are already friends with $user."; exit(); } else { $sql = "UPDATE friends SET accepted='1' WHERE id='$reqid' AND user1='$user' AND user2='$log_username' LIMIT 1"; $query = mysqli_query($db_conx, $sql); mysqli_close($db_conx); echo "accept_ok"; exit(); } } else if($_POST['action'] == "reject"){ mysqli_query($db_conx, "DELETE FROM friends WHERE id='$reqid' AND user1='$user' AND user2='$log_username' AND accepted='0' LIMIT 1"); mysqli_close($db_conx); echo "reject_ok"; exit(); } } ?> user.php <?php include_once("php_includes/check_login_status.php"); // Initialize any variables that the page might echo $u = ""; $sex = "Male"; $userlevel = ""; $country = ""; $joindate = ""; $lastsession = ""; // Make sure the _GET username is set, and sanitize it if(isset($_GET["u"])){ $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']); } else { header("location: http://www.yoursite.com"); exit(); } // Select the member from the users table $sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1"; $user_query = mysqli_query($db_conx, $sql); // Now make sure that user exists in the table $numrows = mysqli_num_rows($user_query); if($numrows < 1){ echo "That user does not exist or is not yet activated, press back"; exit(); } // Check to see if the viewer is the account owner $isOwner = "no"; if($u == $log_username && $user_ok == true){ $isOwner = "yes"; } // Fetch the user row from the query above while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) { $profile_id = $row["id"]; $gender = $row["gender"]; $country = $row["country"]; $userlevel = $row["userlevel"]; $signup = $row["signup"]; $lastlogin = $row["lastlogin"]; $joindate = strftime("%b %d, %Y", strtotime($signup)); $lastsession = strftime("%b %d, %Y", strtotime($lastlogin)); if($gender == "f"){ $sex = "Female"; } } ?><?php $isFriend = false; $ownerBlockViewer = false; $viewerBlockOwner = false; if($u != $log_username && $user_ok == true){ $friend_check = "SELECT id FROM friends WHERE user1='$log_username' AND user2='$u' AND accepted='1' OR user1='$u' AND user2='$log_username' AND accepted='1' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $friend_check)) > 0){ $isFriend = true; } $block_check1 = "SELECT id FROM blockedusers WHERE blocker='$u' AND blockee='$log_username' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check1)) > 0){ $ownerBlockViewer = true; } $block_check2 = "SELECT id FROM blockedusers WHERE blocker='$log_username' AND blockee='$u' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check2)) > 0){ $viewerBlockOwner = true; } } ?><?php $friend_button = '<button disabled>Request As Friend</button>'; $block_button = '<button disabled>Block User</button>'; // LOGIC FOR FRIEND BUTTON if($isFriend == true){ $friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>'; } else if($user_ok == true && $u != $log_username && $ownerBlockViewer == false){ $friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>'; } // LOGIC FOR BLOCK BUTTON if($viewerBlockOwner == true){ $block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>'; } else if($user_ok == true && $u != $log_username){ $block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>'; } ?><?php $friendsHTML = ''; $friends_view_all_link = ''; $sql = "SELECT COUNT(id) FROM friends WHERE user1='$u' AND accepted='1' OR user2='$u' AND accepted='1'"; $query = mysqli_query($db_conx, $sql); $query_count = mysqli_fetch_row($query); $friend_count = $query_count[0]; if($friend_count < 1){ $friendsHTML = $u." has no friends yet"; } else { $max = 18; $all_friends = array(); $sql = "SELECT user1 FROM friends WHERE user2='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user1"]); } $sql = "SELECT user2 FROM friends WHERE user1='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user2"]); } $friendArrayCount = count($all_friends); if($friendArrayCount > $max){ array_splice($all_friends, $max); } if($friend_count > $max){ $friends_view_all_link = '<a href="view_friends.php?u='.$u.'">view all</a>'; } $orLogic = ''; foreach($all_friends as $key => $user){ $orLogic .= "username='$user' OR "; } $orLogic = chop($orLogic, "OR "); $sql = "SELECT username, avatar FROM users WHERE $orLogic"; $query = mysqli_query($db_conx, $sql); while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $friend_username = $row["username"]; $friend_avatar = $row["avatar"]; if($friend_avatar != ""){ $friend_pic = 'user/'.$friend_username.'/'.$friend_avatar.''; } else { $friend_pic = 'images/avatardefault.jpg'; } $friendsHTML .= '<a href="user.php?u='.$friend_username.'"><img class="friendpics" src="'.$friend_pic.'" alt="'.$friend_username.'" title="'.$friend_username.'"></a>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><?php echo $u; ?></title> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="style/style.css"> <style type="text/css"> img.friendpics{border:#000 1px solid; width:40px; height:40px; margin:2px;} </style> <script src="js/main.js"></script> <script src="js/ajax.js"></script> <script type="text/javascript"> function friendToggle(type,user,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $u; ?>."); if(conf != true){ return false; } _(elem).innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "php_parsers/friend_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "friend_request_sent"){ _(elem).innerHTML = 'OK Friend Request Sent'; } else if(ajax.responseText == "unfriend_ok"){ _(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>'; } else { alert(ajax.responseText); _(elem).innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&user="+user); } function blockToggle(type,blockee,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action on user <?php echo $u; ?>."); if(conf != true){ return false; } var elem = document.getElementById(elem); elem.innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "php_parsers/block_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "blocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'unblock\',\'<?php echo $u; ?>\',\'blockBtn\')">Unblock User</button>'; } else if(ajax.responseText == "unblocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'block\',\'<?php echo $u; ?>\',\'blockBtn\')">Block User</button>'; } else { alert(ajax.responseText); elem.innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&blockee="+blockee); } </script> </head> <body> <?php include_once("template_pageTop.php"); ?> <div id="pageMiddle"> <h2><?php echo $u; ?></h2> <p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p> <p>Gender: <?php echo $sex; ?></p> <p>Country: <?php echo $country; ?></p> <p>User Level: <?php echo $userlevel; ?></p> <p>Join Date: <?php echo $joindate; ?></p> <p>Last Session: <?php echo $lastsession; ?></p> <hr /> <p>Friend Button: <span id="friendBtn"><?php echo $friend_button; ?></span> <?php echo $u." has ".$friend_count." friends"; ?> <?php echo $friends_view_all_link; ?></p> <p>Block Button: <span id="blockBtn"><?php echo $block_button; ?></span></p> <hr /> <p><?php echo $friendsHTML; ?></p> </div> <?php include_once("template_pageBottom.php"); ?> </body> </html> notifications.php <?php include_once("php_includes/check_login_status.php"); // If the page requestor is not logged in, usher them away if($user_ok != true || $log_username == ""){ header("location: http://www.yoursite.com"); exit(); } $notification_list = ""; $sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' ORDER BY date_time DESC"; $query = mysqli_query($db_conx, $sql); $numrows = mysqli_num_rows($query); if($numrows < 1){ $notification_list = "You do not have any notifications"; } else { while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $noteid = $row["id"]; $initiator = $row["initiator"]; $app = $row["app"]; $note = $row["note"]; $date_time = $row["date_time"]; $date_time = strftime("%b %d, %Y", strtotime($date_time)); $notification_list .= "<p><a href='user.php?u=$initiator'>$initiator</a> | $app<br />$note</p>"; } } mysqli_query($db_conx, "UPDATE users SET notescheck=now() WHERE username='$log_username' LIMIT 1"); ?><?php $friend_requests = ""; $sql = "SELECT * FROM friends WHERE user2='$log_username' AND accepted='0' ORDER BY datemade ASC"; $query = mysqli_query($db_conx, $sql); $numrows = mysqli_num_rows($query); if($numrows < 1){ $friend_requests = 'No friend requests'; } else { while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $reqID = $row["id"]; $user1 = $row["user1"]; $datemade = $row["datemade"]; $datemade = strftime("%B %d", strtotime($datemade)); $thumbquery = mysqli_query($db_conx, "SELECT avatar FROM users WHERE username='$user1' LIMIT 1"); $thumbrow = mysqli_fetch_row($thumbquery); $user1avatar = $thumbrow[0]; $user1pic = '<img src="user/'.$user1.'/'.$user1avatar.'" alt="'.$user1.'" class="user_pic">'; if($user1avatar == NULL){ $user1pic = '<img src="images/avatardefault.jpg" alt="'.$user1.'" class="user_pic">'; } $friend_requests .= '<div id="friendreq_'.$reqID.'" class="friendrequests">'; $friend_requests .= '<a href="user.php?u='.$user1.'">'.$user1pic.'</a>'; $friend_requests .= '<div class="user_info" id="user_info_'.$reqID.'">'.$datemade.' <a href="user.php?u='.$user1.'">'.$user1.'</a> requests friendship<br /><br />'; $friend_requests .= '<button onclick="friendReqHandler(\'accept\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">accept</button> or '; $friend_requests .= '<button onclick="friendReqHandler(\'reject\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">reject</button>'; $friend_requests .= '</div>'; $friend_requests .= '</div>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Notifications and Friend Requests</title> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="style/style.css"> <style type="text/css"> div#notesBox{float:left; width:430px; border:#F0F 1px dashed; margin-right:60px; padding:10px;} div#friendReqBox{float:left; width:430px; border:#F0F 1px dashed; padding:10px;} div.friendrequests{height:74px; border-bottom:#CCC 1px solid; margin-bottom:8px;} img.user_pic{float:left; width:68px; height:68px; margin-right:8px;} div.user_info{float:left; font-size:14px;} </style> <script src="js/main.js"></script> <script src="js/ajax.js"></script> <script type="text/javascript"> function friendReqHandler(action,reqid,user1,elem){ var conf = confirm("Press OK to '"+action+"' this friend request."); if(conf != true){ return false; } _(elem).innerHTML = "processing ..."; var ajax = ajaxObj("POST", "php_parsers/friend_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "accept_ok"){ _(elem).innerHTML = "<b>Request Accepted!</b><br />Your are now friends"; } else if(ajax.responseText == "reject_ok"){ _(elem).innerHTML = "<b>Request Rejected</b><br />You chose to reject friendship with this user"; } else { _(elem).innerHTML = ajax.responseText; } } } ajax.send("action="+action+"&reqid="+reqid+"&user1="+user1); } </script> </head> <body> <?php include_once("template_pageTop.php"); ?> <div id="pageMiddle"> <!-- START Page Content --> <div id="notesBox"><h2>Notifications</h2><?php echo $notification_list; ?></div> <div id="friendReqBox"><h2>Friend Requests</h2><?php echo $friend_requests; ?></div> <div style="clear:left;"></div> <!-- END Page Content --> </div> <?php include_once("template_pageBottom.php"); ?> </body> </html>
thumb

PHP Videos

Social Network Development

Introduction and Building the Design TemplateDatabase Creation and PHP MySQLi Connection Script TutorialMySQL Database Tables Creation Script LogicEstablish htaccess and phpini for apache web site server configurationCreate the Main JavaScript Module and Insert Other Modules TutorialSign Up Form and Email Activation PHP MySQL JavaScript Programming TutorialLog In Form Log Out Script Cookies Sessions User ProfileCron Job Automate Social Network Web Site Maintenance TutorialForgot Account Password Form Email Script Ajax TutorialFriend Add Block System Ajax TutorialSocial Network Header Logic Dynamic Links Example ScriptFriend Lists and Social Network Notifications TutorialUser Profile Photo File Upload HTML Form PHP Parse Script MySQLPhoto Gallery CMS TutorialConversation System Social Network Ajax PHP MySQL TutorialSend SMS Text Messages to Mobile Phone PHP Tutorial