You are on page 1of 83

1

The Social Network Scripts For Beginners


This EBook is to teach newbie web programmers how to create a social
network platform either for their school project or for their personal interest in php
and JavaScript. This eBook explained how to create a social forum sharing
message in php, JavaScript, MYSQL and HTML.
The codes are all written in simple php and JavaScript programming languages
that can be understood by those who are new in web programming. Each chapter or
feature is being explained how the code is being written or coded and how that
feature works. Have it in mind that it teaches you how to create your own photo
sharing and discussion forum on the Internet where people can use it just like any
other social network forums that exist.
The codes of this EBook were written by a group of programmers (Lano Demi,
Milow Wood and N. Albert) who wish to teach and reduce the heavy task or
bulkiness of someone that want to develop a social network forum. The creation of
a social network forum is not that easy, it requires a lot of time and energy to
establish it. Due to the complexity of an individual to solemnly create a social
network forum on the Internet, we have came up with a great way and an idea to
write this EBook called Social Network Script for Beginners in order to
provide a descriptive way that you can code your own social network forum within
a month. This Ebook contains scripts that have been tested and used; it is
compactable with Firefox, Internet Explorer, Safari, Google chrome and Opera
mini browsers.
Our aimed is to facilitate the bulkiness of creating the social network forum. If
you follow this EBook from scratch to the end you will have the skill to build not
only a social network forum, but many others related web applications using the
2

ideas and tricks you will obtain from this EBook as you follow the tutorial in this
EBooks.

How to use and read this EBook


The codes written for this EBook are explained or commented beside each line
of the code like this //this is the comment about the line of code. It is usually
colored in red or green. When you see comment like this //this is the comment
about the line of code beside any line of codes, know that it explains how the code
works or reasons why it was coded in such format. For example,
<? php
$mysql_hostname = "localhost"; // server of the database
$mysql_user = "root";
$mysql_password = ""; // password of the database
$mysql_database = "learn"; //name of the database
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user,
$mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select
database");
?>
From the above php script, you can see that comments or explanations have
been made in the format above like this // server of the database. This is to explain
to you the meaning of the line of code, and it uses. This format of explaining,
describing or commenting codes is what will be used to explain the codes
throughout this eBook so that you can understand the scripts that have been
3

written. Also, you can eliminate this comment or explanation to copy it to your
text editor in order to see how this codes works. For example, this is the php script
that the comment or explanation text has been removed.
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "learn";
$prefix = "";
$bd = mysql_connect ($mysql_hostname, $mysql_user,
$mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select
database");
?>
From the above code you can see how the comments or explanations of the code
have been removed when it was copied on to the text editor in order to see how it
works or to run the script. You can also do the same too to test and see how the
script works.
We recommend that you read this EBook in an undistracted atmosphere as we all
know that learning programming requires a quit atmosphere so that you understand
every codes written for this project.

Table of contents
Chapter one:
Database used for this tutorial.php 7
Connection.php. 10
4

Function.php. 11
Registration Form and script. 13
Login form and script 25

Chapter Two:

View profile name and photo 32


See people you may know. 35
Upload profile picture 38
Live search engine. 44
View others user informations.. 50

Chapter Three:

Friend relationship system. 54


View friend request script. . 59
Add friend script. 63
Reject friend request script. 64
View friends script.. 65

Chapter Four:

Post on timeline and to a friend timeline. 68


View and add comment related to a friend post.. 74
Send a private message 76
View private message you sent 79
View private message someone sent to you. 82
Logout... 86

DATABASE used for this tutorial


Below are the table names of the database (learn) which we are going to use
in this tutorial.
The table below is where the register and login user informations are
being kept. It has the name member.
CREATE TABLE IF NOT EXISTS `member` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(30) NOT NULL,
`secondname` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`sex` varchar(100) NOT NULL,
`password` varchar(30) NOT NULL,
`profile_picture` varchar(30) NOT NULL,
`day` varchar(100) NOT NULL,
`month` varchar(30) NOT NULL,
`year` varchar(100) NOT NULL,
PRIMARY KEY (`member_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=21 ;

This is the table where the friend request will be kept. It has the name
friendship.
CREATE TABLE IF NOT EXISTS `friendship` (
`friend_id` int(11) NOT NULL AUTO_INCREMENT,
`receiver` varchar(30) NOT NULL,
`sender` varchar(30) NOT NULL,
PRIMARY KEY (`friend_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=3;
This is the table where the friends (those who are) will be kept. It has the
name myfriends.
CREATE TABLE IF NOT EXISTS `myfriends` (
`friend_id` int(11) NOT NULL AUTO_INCREMENT,
`myid` varchar(30) NOT NULL,
`myfriends` varchar(30) NOT NULL,
PRIMARY KEY (`friend_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=14 ;
This is the table where the post messages will be kept. It has the name post.
CREATE TABLE IF NOT EXISTS `post` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`commenttext` varchar(30) NOT NULL,
`me` varchar(30) NOT NULL,
`date` varchar(100) NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
AUTO_INCREMENT=2 ;
This is the table where the add comment text that is related to a post
message will be kept. It has the name postcomments.
CREATE TABLE IF NOT EXISTS `postcomments` (
`postcommentid` int(11) NOT NULL AUTO_INCREMENT,
`postid` int(11) NOT NULL,
`memberid` int(11) NOT NULL,
`date` date NOT NULL,
7

`comment` varchar(5000) NOT NULL,


PRIMARY KEY (`postcommentid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=5 ;
This is the table where the private message will be kept or store. It has the
name messages.
CREATE TABLE IF NOT EXISTS `messages` (
`messageid` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` varchar(5000) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`postcommentid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=5;

Connection.php
This file connects the social network to the database. It is made of
localhost, root and database name. It has no password. The name of the
database is learning that contain other tables such as member, post,
friendship, postcomment and myfriends tables.
<?php
$mysql_hostname = "localhost"; // server of the database
$mysql_user = "root";
$mysql_password = ""; // password of the database
$mysql_database = "learn"; //name of the database
$prefix = "";
8

$bd = mysql_connect($mysql_hostname, $mysql_user,


$mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select
database");
?>

Function.php
To commence (start) the journey of this social network EBook, first you
must have a folder call easygoing or you can better name the folder with
your own name that you like. This folder will be the folder that will contains
all the files and other sub-folders. After creating the main folder that will
contains all the files and sub-folders, you have to now create a file call
function.php. This file contains only the information or ID (member_id) that
have been extracted (collected) from the database with the table name called
member which will be used to track or identify only the login user that is
the owner of the ID (member_id) or login session. This file should be
included in all the pages that we work with except with the index. Php page
function.php
<?php
include("connection.php"); // include file to connect to the database.
if(isset($_SESSION["SESS_FIRST_NAME"])) {

$result = mysql_query("SELECT member_id FROM `member`


WHERE `email`='".$_SESSION["SESS_FIRST_NAME"]."' LIMIT 1");
///This section selects from the database having the table name member
where the row of the table called email that the user used to login belongs or
matches the member_id of the table called member.
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$_SESSION["logged"] = $row["member_id"]; // This is the unique
member number (member_id ) that belong to the login user which has been
extracted from the table called member where the login user informations
are being kept. It has been assign to the variable $_SESSION["logged"]
which will be used to all others pages on this project to identify the login
user with his unique number ($row["member_id"];)
}
}
?>

10

The registration page

Now create a page call index.php that will contain the registration form.
This chapter covers the creation of new user registration on this application.
The registration form will usually go to the index.php where new user can
register on the site. The registration form is created with HTML and it is
validated with JavaScript. Below is the example of how the index.php page
look like.
<?php
//Start session
session_start();
//Unset the variables stored in session
unset($_SESSION['SESS_MEMBER_ID']);
unset($_SESSION['SESS_FIRST_NAME']);
unset($_SESSION['SESS_LAST_NAME']);
?>

11

//This code will probably be used to start and check the session of the login
user //unset($_SESSION['SESS_MEMBER_ID']);//
//unset($_SESSION['SESS_FIRST_NAME']);//
// unset($_SESSION['SESS_LAST_NAME']); // The above line of codes
help to echo or print the error message that occur when the login user has an
error in logging in.
<HTML>
<head>
</head>
</body>
This is the registration form with the name myForm and action
exec.php, the onsubmit="return(validate());" //is used to validate the form
in JavaScript.
Index.php page
<html>
//registration form
<form name="myForm" action="exec.php" onsubmit="return(validate());"
method="post">
<br>
<input type="text" name="firstname" size="49" style="height:30;"
placeholder="FIRST NAME" class="reg"><br>
<br>
<br>
<input type="text" name="secondname" size="49" style="height:30;"
placeholder="SECOND NAME" class="reg"><br>
<br>
<br>
<input type="text" name="email" size="49" style="height:30;"
placeholder="EMAIL" class="reg"><br>
<br>
12

<br>
<td><input type="password" name="password" size="49"
style="height:30;" placeholder="PASSWORD" class="reg"><br>
<br>
<br>
<input type="password" name="retype" size="49" style="height:30;"
placeholder="RE-TYPE PASSWOED" class="reg"><br><br>
Male<input type="radio" name="sex" value="male">
Female<input type="radio" name="sex" value="female"><br><br>
<font color="green">Born on</font><br>
Day<select name="day">
<option>1</option>
<option>2</option>
</select>
Month<select name="month">
<option>January</option>
<option>February</option>
</select>
Year<select name="year" >
<option>1911</option>
<option>1910</option>
</select><br/><br>
<br>
<input type="hidden" name="profile_picture" value="p.jpg">
// this input type hidden is use to hide the input field that will insert a
default name of the profile image of the entire users before they can change
their profile picture in the database.
<td><input name="submit" type="submit" value="Submit"
id="sum"/></td>
13

</form>
</body>
</html>

JavaScript validation
This JavaScript should be added on the index page between the <head></head>
tags which will validate the registration form.
Below is the JavaScript validation script to validate the registration form. The
JavaScript will validate the form input fields like first name, second name, email,
password, Retype password and gender are empty. And also, it validate to check
whether the password matches to the re-type password and it also check if the
email is a valid email that has @ or ends with .com.

<script type="text/JavaScript">
function validate()
{
var x=document.myForm.firstname.value; //This is the variable (x) assign to the
first name of the registration form that will validate the user first name.
if(x=="") //This is to check if the variable (x) is empty.
{
alert("First name must be filled out"); // If the variable (x) is empty, the user will
be alerted the name must be filled out.
14

return false;
}
var s=document.myForm.secondname.value; //This is the variable (s) assign to
the second name of the registration form that will validate the user second name.
if(s=="") //This is to check if the variable (s) is empty.

{
alert("second name must be filled out");// If the variable (s) is empty, the user
will be alerted the second name must be filled out.
return false;
}
var e=document.myForm.email.value; //This is the variable (e) assign to the
email of the registration form that will validate the user email.
if(e=="") //This is to check if the variable (e) is empty.
{
alert("email must be filled out"); // If the variable (e) is empty, the user will
be alerted the email must be filled out.
return false;
}

15

var p=document.myForm.password.value; //This is the variable (p) assign to


the password of the registration form that will validate the user password.
if(p=="") //This is to check if the variable (p) is empty
{
alert("password must be filled out"); // If the variable (p) is empty, the user
will be alerted that password must be filled out.
return false;

}
var p=document.myForm.retype.value; //This is the variable (p) assign to
the Re-type password of the registration form that will validate the user Re-type
password.
if(p=="") //This is to check if the variable (p) is empty
{
alert("Retype password must be filled out"); // If the variable (p) is empty,
the user will be alerted that password must be re-type.
return false;

16

var pa=document.myForm.password.value; //This is the variable (pa)


assign to password on the registration form that will validate the user password.
var pass=document.myForm.retype.value; //This is the variable (pass)
assign to the re-type password of the registration form that will validate the user retype password.
if(pa!=pass) // It checks if the variable (pa) does not matches to the
variable (pass) .
{
alert("Password does not matched"); // If the variable (pa) does not matches
to the variable (pass), the user will be alerted that Password does not matched.
return false;
}
var email=document.forms["myForm"]["email"].value; //This is the
variable (email) assign to email of the registration form that will validate the user
email.
var atpos=x.indexOf("@"); // It checks if the @ sign is absent.
var dotpos=x.lastIndexOf(".");// It checks if the dot (.) sign is absent.
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
17

}
var sex=document.myForm.sex.value; //This is the variable (sex) assign to the
first name of the registration form that will validate the user sex.
if(s=="") // It checks if the variable (sex) is empty or has not be selected.
{
alert("sex must be selected"); // If the variable (sex) is empty, the user will
be alerted sex most be selected.
return false;
}
}
</script>
For the registration process to be successful the exec.php file is created. This
file collects all the user information from the registration form and registered or
stored it on the table name called member in the database.

This is the exec.php file


<?php
session_start();
include('connection.php'); // This line of code connects to the database .
$firstname=$_POST['firstname'];

18

$secondname=$_POST['secondname'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$password=$_POST['password'];
$photo=$_POST['profile_picture'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$query = mysql_query("SELECT * FROM member WHERE
`email`='$email' "); //This line of code check if the email address has been already
been taken or be used by another user.
if(mysql_num_rows($query) > 0){
echo"
<script type=\"text/javascript\">
alert(\"Please this email address already existed / try another email\"); // this line of
JavaScript code alert a message that the email already exist in the database.
window.location='index.php'; // It returns the user back to the index page when the
email already exist in the database.
</script>
";
19

}
/* If the email of the sign up user does not exist in the database, the information of
the user can now be stored or register in the database with the table name called
member. */
else{
mysql_query("INSERT INTO member(firstname, secondname, email,
sex, password, profile_picture, day, month, year)
VALUES('$firstname', '$secondname', '$email', '$sex', '$password',
'$photo', '$day', '$month', '$year')");
header("location: home.php"); The sign up user will now be sent to the home.php
page after registration.
mysql_close($con);
//Create query
$qry="SELECT * FROM member WHERE email='$email' AND
password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result)
{
if(mysql_num_rows($result) > 0)
20

{
//register Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['email'];
$_SESSION['SESS_LAST_NAME'] = $member['password'];
session_write_close();
exit();
}
}
}
?>

Login form and processes


21

After when the user has registered and want to open his account without
creating another account, the user may need to login not register again. Below are
the various steps for creating the login form and php script. First, add this code on
the index.php page. It contains the login form and it validations. The login form
name is loginform, the action of the form is loginscript.php that contains the php
script for validating the user information whether it is missing from the input field
and in the database. If it is not in the database it echoes an error message to the
user.
<div style="position:absolute; left:339; top:30;" id="log">
<form name="loginform" action="loginscript.php" method="post">
<table width="113%" height="221%" frame="void">
<td colspan="2">
<!--the code bellow is used to display the message of the input validation if
there are any errors-->
<?php
if( isset($_SESSION['ERRMSG_ARR']) &&
is_array($_SESSION['ERRMSG_ARR']) &&
22

count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
</td>
</tr>
<tr valign="top" width="45" height="15">
<td align="left" width="6"><font size="6"
color="green"><b>login</b></font>
</td></tr>
<tr>
<td>email<br><input type="text" name="email"
placeholder="email" size="39" style="height:29;"
class="reg"></td>
</tr>
<td>Password<br><input type="password" name="password"
placeholder="password" size="39" style="height:29;"class="reg">
<br><br>
<input type="submit" value="login" id="login_button"></td>
</tr>
</table>
</form>
</div>

23

Loginscript.php
The loginscript helps to check if the login user has an email and password
that exist in the database.
<?php
session_start(); //Start session
require_once('connection.php'); //Include database connection details
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
24

}
return mysql_real_escape_string($str);
}

//Sanitize the POST values.


$email = clean($_POST['email']);
$password = clean($_POST['password']);

//Input Validations
if($email == '') {
$errmsg_arr[] = 'email missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form.
if($errflag) {

25

$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php"); //if the input validation errors, the user is being
taking to the index.php
exit();
}

//Create query
$qry="SELECT * FROM member WHERE email='$email' AND
password='$password'";
$result=mysql_query($qry);

//Check whether the query was successful or not.


if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful.
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['email'];
26

$_SESSION['SESS_LAST_NAME'] = $member['password'];
session_write_close();
header("location: home.php"); /* when the user information is available in the
database and when it passed the validation checks, it will take the user to the
home.php page where the user can access his/her account. */
exit();
}else {
//Login failed.
$errmsg_arr[] = 'email and password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php"); /* this takes you to the index. Php page when you
have an error usually when you provide wrong information that is no available in
the database or when you submit an empty login form field. */
exit();
}
}
}else {
27

die("Query failed");
}

?>
Show the login user profile name and picture

A page called home.php page is created and after when the login user has login
into he/her account the profile name and photo have to be shown to the current user
that just login. At the top of the home.php page before the <html> tag place this
php code below.

<?php

session_start();/// start the session of the ligin user.


include("connection.php"); /* this file connects the database to this home.php
page */
include("function.php"); /* this file collect the login user id from the table called
member that has the value like this member_id(auto increment) */
include("insert.php"); /* this file insert post texts and comment text into the
database.*/
?>
The code below extracts the only the login user name and photo from the
database.
28

<html>
<head>
</head>
<body>
<?php
include("connection.php"); // Includes the file connect.php to connect to database
if(isset($_SESSION["SESS_FIRST_NAME"])) // Starting session cookies
//Checking if they have the session cookie taking from the loginscript.php.
{
$result = mysql_query("SELECT * FROM `member` WHERE

`email`='".

$_SESSION["SESS_FIRST_NAME"]."' LIMIT 1"); /* this line of code selects


from the database with a table name called member that contains all the login user
information where the email in the member table belongs to the session cookie of
the login user that is taking from the loginscript.php. */
echo "<table border='0px' id='profilename' style='position:absolute; margin:4px
0px 0px 8px;'>
";

while($row = mysql_fetch_array($result))
29

{
echo "<tr>";
echo"<div align='left'><img src='./uploads/p.jpg' width='170' height='170px'
style='position:absolute; margin:30px 0px 0px 13px;' /></div>";
echo "<img src='uploads/".$row['profile_picture']."' width='170px' height='170px'
style='position:absolute; margin:30px 0px 0px 13px;'>";/*this line of code select
the name of the user profile photo from the database and the photo is stored in the
folder called uploads.*/
echo "<td>" . $row['firstname'] . "</td >";// echo the first name of the user.
echo "<td>". $row['secondname'] ."</td>";// echo the second name of the user.
echo "</tr>";
}
echo "</table>";
}

?>

</body>
</html>

30

The people you may know

People you may know script selects other users from the database and show them
to you if you know them so that you can add them as your friends. This is the script
below.
<?php
/* Below line of code selects from the database with the table called member
where the login user cannot appear on people you may know because he or she
cannot add himself/herself as friend. */

31

$result= mysql_query("SELECT * FROM `member` WHERE `email`!='".


$_SESSION["SESS_FIRST_NAME"]."' LIMIT 10"); /* this line of code select
people from the database where their emails does not belong or match to the login
user. */
while($row=mysql_fetch_array($result))
{
echo '
<div align="left"><img src="uploads/'.$row['profile_picture'].'" alt="" height="54"
width="60" style="position:absolute; margin:24px 0px 0px 70px;" /></div>
<div align="center">
/* this line of code below contains link that when you click it shows you all the
information of the user that you have just clicked. The file friendinfo.php will take
the login user to another page where the login user will see the information of the
person he/she has clicked. The amifo amifo='.$row["member_id"]. below is the
user number on the member table of the database member_id that is particular to
that user. */
<ahref="friendinfo.php?amifo='.$row["member_id"].'">'.$row['firstname']." ".
$row['secondname'].'</a></di>
<div align="left">'."<input type='hidden' id=".$row['secondname'].'"></div>
/* below contain a link that when you click it create a friend request. The file
process.php contains script that will check if that person is your friend, already
your friend or the person want to be your friend.The '.$row["member_id"]. below

32

is the user number (member_id) which you which to send a friend request to on the
member table of the database member_id that is unique to that user. */
<a href="process.php?send='.$row['member_id'].'" style="textdecoration:none;"><button style="width:60px; height:40px;" >Add
Friend</button></a>
<hr width="158" align="left" style=" margin:22px 0px 0px 0px;">
<br>
';
}
?>

33

Uploading profile picture

Now is time for the user to upload he/her profile photo. To upload photo, we need
to create a form to allow user to select and upload photo a profile photo. The
upload_photo.php in the form is a php file that validate the file if it is a picture or
not and it will also validate the picture size as well as it will insert the profile photo
into the database.
<div id="upload_picture">
<form action="upload_photo.php" enctype="multipart/form-data" method= "post"
style="margin:10px 0px 0px 10px;">
<input name="MAX_FILE_SIZE" type="hidden" value="1000000">
<input id="upload_file" name="file" type="file"><br><br>
<button type="button">Close</button>

34

<button name="savephoto" type="submit">Save Photo</button>


</form>
</div>

upload_photo.php
This php file (upload_photo.php) contains script that is use to validate and insert
the login user profile picture into the database with the table name called member
and the name of the row is profile_picture.
upload_photo.php
<?php
include("connection.php");///connect to the database
include("home.php"); /* it include the home page because the login user id which
is member_Id is require to insert only the login user of that id photo into the
database. */
$me= $_SESSION["logged"]; /* This is the login user id that is being collected
from the include(home.php); This login user id indicate that the user of this id is
the one that is uploading the profile photo. It has the variable of $me. */

35

$path = "uploads/"; /* this line of code is where the login user uploaded photo will
be stored it has the variable of $path. The folder where the profile picture will be
kept is uploads. */
$valid_formats = array("jpg", "png", "gif", "bmp");/* this line code check the valid
format of the photo that should be uploaded. It has the variable $valid_formats. */
If(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['file']['name'];/* this is the photo name that will be uploaded
with the variable $name. */
$size = $_FILES['file']['size']; /* this is the photo size that will be uploaded with
the variable $size. */
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
/* below is the line of code that has the variable $actual_image_name of the photo
name. */
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
36

$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) /* this line of code
move the uploaded photo into the folder called uploads where it will be store. */
{
//below is the sections that insert the photo in to the database.
mysql_query("UPDATE member SET profile_picture='$actual_image_name'
WHERE member_id='$me'"); /* this line of code inserts the name of the photo
with the variable called '$actual_image_name' into the table called member having
the value called profile_picture and the id(member_id) of the login user who
inserting the profile photo into the database. The member_id='$me' is the login
user number( member_id ) that will be inserted in to the database to identify the
that it is login user that uploaded the profile picture.. */
echo "<img src='uploads/".$actual_image_name."' >";/* this line of code collects
the photo from the stored folder and show it to the login user profile photo. */
echo "<script type=\"text/javascript\">//JavaScript
alert(\"photo has been uploaded\");/* this echo a message if the photo has been
uploaded successfully. */

window.location='home.php';/* it takes the user back to the home.php page after


uploading the photo. */
</script>";
}

37

Else

echo "<script type=\"text/javascript\">


alert(\"photo uploaded failed\");/* this echo a message if the photo has not been
uploaded successfully. */
window.location='home.php';
</script>";
}
else
echo "<script type=\"text/JavaScript\">
alert (\"photo uploaded too big\");/* this echo a message if the photo size is too big
to be uploaded. */

window.location='home.php';
</script>";
}
else
echo "<script type=\"text/javascript\">
alert(\"photo uploaded invalid\");//this echo a message if the file is not a photo
formats.

38

window.location='home.php';
</script>";
}
else
echo "<script type=\"text/javascript\">
alert(\" Select a photo\");/* this echo a message if the the photo has been not been
selected to be uploaded. */

window.location='home.php';
</script>";
exit;
}
?>

39

Search engine

This part shows you how to find friend from the database. The search engine is
being coded with Jquery. As you type the name of the person you want to search, it
instantly brings you the person name and profile photo with a link that when you
click it takes you to the page where the information of the person whom you search
will be shown to you and a button of friend request. When searching, the page does
not refresh. It is a live search engine.

Next is the external link of the Jquery.

40

Due to the bulkiness of this code we cannot add this external Jquery file on this
eBook but, you can contact us via this email easygoing@gmail.com to download
the code.
You can still download the jquery-1.8.0.min.js. Place this external link in between
the open and close header codes.<head></head>
<script type="text/javascript" src="script/jquery-1.8.0.min.js"></script>

Below is the search engine form


<div id="noticeboard">
<div class="content">
<input type="text" class="search" id="searchid"
placeholder="Search for people" />
&nbsp; &nbsp; search engine<br />
<div id="result">
</div>
</div>
</div>

41

Below is the php search engine script that collects the search names from the
database.

Search.php
<?php
include('connecti.n.php');//This file connects the search.php to the database.
if($_POST)
{
$query=$_POST['search'];/* this line of code that has the variable $query is the
name of other users in the database that the login user searches. */
$sql = mysql_query("SELECT * FROM `member` WHERE `firstname` LIKE '%
$query%' OR `secondname` LIKE '%$query%' LIMIT 0, 5 ") or die
(mysql_error()); /* this select from the data base the first and second name that the
login user type in the search field. */
$num_of_row = mysql_num_rows($sql);

42

if ($num_of_row > 0 ){
while($row = mysql_fetch_array($sql))
{
$id = $row['member_id']; /* this select the search user id(member_id) from the
member table which has been assign with the variable $id. */
echo "<img src='uploads/".$row['profile_picture']."' width='50' height='50'
style='position:relative; margin:-6px 0px 0px 3px;'>";
<!-- Below is the link that when you click it takes you to the page called
friendinfo.php where all the information of the user will be shown to the login user.

echo "<a href='friendinfo.php?amifo=".$id."' style='color:blue; textdecoration:none;'>&nbsp;". $row['firstname']."&nbsp;".


$row['secondname']."</a>";
echo "<hr width='600px'>";
}
}
else
{
echo "<font color='red' size='4' >No result found!</font>";/*this line of code show
the text No result found! if there is no result found. */
}
43

}
?>
The next is the Jquery script that shows the result without reloading or refreshing
the page. Place this script below on the home.php page.
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php", //this is the php file above that select the search name from
the database.
data: dataString,
cache: false,
success: function(html)
{
44

$("#result").html(html).show();
}
});
}return false;
});

jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
45

jQuery("#result").fadeIn();
});
});
</script>

How to see other users informations

When login user click on any user name whether he/she are friend or not in
below code, the login user will be taken to a page called friendinfo.php where the
login user can view the user email, date, month, year and place of birth.

<?php

46

$result= mysql_query("select * FROM `member` WHERE `email`!='".


$_SESSION["SESS_FIRST_NAME"]."' LIMIT 10");
while($row=mysql_fetch_array($result))
{
echo '
<div align="left"><img src="uploads/'.$row['profile_picture'].'" alt="" height="54"
width="60" style="position:absolute; margin:24px 0px 0px 70px;" /></div>
<div align="center">
<ahref="friendinfo.php?amifo='.$row["member_id"].'">' /* On this line of code is
the user id(member_id) that login user want to see his/her informations. When the
login user click the person name, it will take the login user to the page called
friendinfo.php where the login user can see the user informations. */
".$row['secondname'].'</a></di> <div align="left">'."<input
type='hidden' id=".$row['secondname'].'"></div>
<a href="process.php?send='.$row['member_id'].'" style="textdecoration:none;"><button style="width:60px; height:40px;" >Add
Friend</button></a>
0px 0px 0px;">
<br>
';

47

<hr width="158" align="left" style=" margin:22px

}
?>

Below is the friendinfo.php page where the login user can see the user
information that he/she have clicked.
First, at the top of the friendinfo.php page before the Doctype Elements place
this php code.
<?php
session_start();
include("connection.php"); /// this line of code connects you to the database.
include ("function.php"); /* this is the function file that collects the login user
id (member_id ) from the database. It will be used to identify the unique login user.
*/

$friend1=$_GET['amifo'];/* this is the user id (member_id ) that the login


user want to see his/her informations when he/she click the user name. */

$me=$_SESSION["logged"];// this is the login user id


?>
<html>
<head>
48

(member_id)

</head>
<?php
$post = mysql_query("SELECT * FROM member WHERE
member_id = '$friend1' OR member_id = '$friend1'")or
die(mysql_error());

$row = mysql_fetch_array($post); ?>

Name: &nbsp;<strong><?php echo $row['firstname']."


".$row['secondname'];?>&nbsp;&nbsp;</strong>
email:&nbsp; <strong><?php echo
$row['email'];?></strong>&nbsp;&nbsp; &nbsp;&nbsp;
Date of birth: <strong>&nbsp; <?php echo $row['day'];?>
</strong>&nbsp;&nbsp;
Month of birth: <strong>&nbsp; <?php echo $row['month'];?>
</strong>&nbsp;&nbsp;&nbsp;&nbsp;
Year of birth: <strong>&nbsp; <?php echo '<img
src="uploads/'.$row['profile_picture'].'" alt="" height="370"
width="370" style="position:absolute; margin:70px 0px 0px -583px;" />';
?>
</strong> &nbsp;&nbsp;
</body> </html>
49

FRIEND RELATIONSHIP SYSTEMS


This is one of the most difficult parts of this social network script. It is very
complex but very simple to understand. Do not worry because we have coded it in
a very simple and understanding format. The first step of the friend relationship
system is to create a friend request system where the user can send a friend request
to someone or someone can send a friend request to the login user. The second is
for the login user to accept any friend request or someone to accept the login user
friend request.
We will get start with the friend request system.

First a table is created called friendship in the database. This is how the table
looks like:
50

CREATE TABLE IF NOT EXISTS `friendship` (


`friend_id` int(11) NOT NULL AUTO_INCREMENT,
`receiver` varchar(30) NOT NULL, /* this is the id of the user you are sending the
friendrequest */
`sender` varchar(30) NOT NULL, /* this is your id(member_id) that you use to
send friend request. */

PRIMARY KEY (`friend_id`)


) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Below is the script that shows people the login user may know which he/she can
add some of them as friend. This script has been explained above from the people
you may know script. We explained only the friend request portion of this script.
The key step to create a friend request system is to get the id(member_id ) of the
user and the login user id (member_id) and insert it into the database.

<?php
$result= mysql_query("select * FROM `member` WHERE `email`!='".
$_SESSION["SESS_FIRST_NAME"]."' LIMIT 10");
while($row=mysql_fetch_array($result))
{
echo '
51

<div align="left"><img src="uploads/'.$row['profile_picture'].'" alt="" height="54"


width="60" style="position:absolute; margin:24px 0px 0px 70px;" /></div>
<div align="center"><a href="friendinfo.php?amifo='.$row["member_id"].'">'.
$row['firstname']." ".$row['secondname'].'</a></div>
<div align="left">'."<input type='hidden' id=".$row['secondname'].'"></div>
<a href="process.php?send='.$row['member_id'].'" style="textdecoration:none;"><button style="width:60px; height:40px;" >Add
Friend</button></a>/* this link contains the id (member_id) which is shown as
send='.$row['member_id'].Of the user that the login user want to add as friend.
This id (member_id) will be stored in the database with the name friendship and
the value `receiver`. The process.php file has the code which will insert the user
value into the database. */
<hr width="158" align="left" style=" margin:22px 0px 0px 0px;">
<br>
';
}
?>
Process.php
This file contains the codes that validate the friend request. It will check if the
person is your friend, or the login user has already send a friend request, or if the
person is the login user friend and then insert both the login user and the user that
want to be friend in the database when all the validations have been checked.

52

<?php
include("connection.php");//It connects the to the database.
include("home.php");
$receiver=$_GET['send']; /* This is the id (member_id) of the user that the login
user want to add as friend which have the variable $receiver. */
$sender= $_SESSION["logged"]; /* this line of code contains the login user id
(member_id) that will be inserted into the table called friendship having the value
`$sender`. */
$query = mysql_query("SELECT * FROM friendship WHERE receiver = '" .
$_SESSION["logged"] . "' AND sender = '" . $_GET['send'] . "' OR receiver = '" .
$_GET['send'] . "' AND sender = '" . $_SESSION["logged"] . "' "); /* This line of
code check if the login user has already send a friend request to the user he/she
want to be friend with. */
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_array($query);
echo"
<script type=\"text/javascript\">//javaScript
alert(\"Friend requesr already sent\"); /* it echoes (print) the message that your
friend request have been already send. */
window.location='home.php';
</script>

53

";
}
else{
/* Below is another table called myfriends(this table is located above) which keep
the user id(member_id ) and the login user id (member_id) when they are friends.
The table has the value myfriends and myid that store the login user id
(member_id) and the user that the login user added as friend. */
$query = mysql_query("SELECT * FROM myfriends WHERE `myid`='" .
$_SESSION["logged"] . "' AND `myfriends`='" . $_GET['send'] . "' OR`myid`='" .
$_GET['send'] . "' AND `myfriends`='" . $_SESSION["logged"] . "'"); /* this line
of code check if the login user are already friend with the user that the login user
want to send friend request. */
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_array($query);
echo"
<script type=\"text/javascript\">
alert(\"Is already your friend\"); /* Echo the message that the user the login user
has sent a friend request is already the login user friend. */
window.location='home.php';
</script>
";

54

}
else
{
mysql_query("INSERT INTO friendship(receiver,sender)
VALUES('$receiver','$sender') ") or die(mysql_error()); /* this line of code insert
the user id (member_id) and yours into the friendship table to create the friend
request system. */
{
echo "<script type=\"text/javascript\">
alert(\"friend request sent\");
window.location='home.php';
</script>";
}
}
}
?>

Show friend Request

55

This part is to show if the login user has any friend requests pending. If someone
sends the login user a friend request the script below will show the login user the
person that has sent the friend request. Now a file is created called friends.php
which show the login user those who want to be his/her friends. On this file
(friends.php) insert this php script below.
<?php
session_start();
include("connection.php");
include("function.php");
?>
Insert the above PHP script at the top of the file (friends.php). Remember to insert
this script to all the pages that you will be working with. After that, below is the
script to show the login user if he/she has any friend request from somebody.

Php Script to show friend request

<?php
56

$member_id=$_SESSION["logged"]; /* this is the login user (member_id) that is


collected from the include(function.php). It has a variable $member_id assign to
the value $_SESSION["logged"]; */
$query = mysql_query("SELECT * FROM friendship WHERE receiver =
'$member_id'"); // this line of code selects from the friendship table with a column
called receiver which is assign to the variable $member_id. if the login user id
(member_id) is found on this column then the login user have friend request from
somebody.
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_array($query))
{
$_query = mysql_query("SELECT * FROM member WHERE member_id = '" .
$row["sender"] . "'
while($_row = mysql_fetch_array($_query))
{
echo '
<div align="left"><img src="./uploads/p.jpg" width="70"
style="position:absolute; margin:10px 0px 0px 3px;" /></div>

57

<div align="left"><img src="uploads/'.$_row['profile_picture'].'" alt=""


height="70" width="70" style="position:absolute; margin:10px 0px 0px 3px;"
/></div>
<div style="position:absolute; margin:10px 0px 0px 83px;"><a
href="friendinfo.php?amifo='.$row["sender"].'">'.$_row['firstname']." ".
$_row['secondname'].'</a> want to be friends with you</div>';

echo'<div id="shiftlinks"><a href="add_friend.php?accept=' .$row['sender'].'


">Accept</a></div>';//this line of codes contains the button for accepting friend
request. It has a link connected to the file add_friend.php that when the login user
click the accept friend request button it will create a friendship, that is both will
become friends.
echo'<div id="shiftlinks1"><a href="reject_friend.php?accept=' .
$row['sender'].'">Reject</a></div>'; ;//this button to reject friend request. It has a
link connected to the file reject_friend.php that when the login user click the reject
button it will reject the friend request.
echo'<hr>';
}
}
}else{
echo 'You do not have any friend pending </li>';
}

58

?>

add_friend.PHP
This is the file (add_friend.php) that inserts the login user id (member_id) and the
user id (member_id) that he/she want to be friend with into table name called
myfriends to create a friendship system.
<?php
include("connection.php");
include("home.php");
$myfriend=$_GET['accept'];
$me= $_SESSION["logged"];
$mfriends=mysql_query("INSERT INTO myfriends(myid,myfriends)
VALUES('$me','$myfriend') ")or die(mysql_error()); // This line of code inserts
into the table name myfriends where anybody the login user add as friends friends
will be kept.
$query = mysql_query("delete from friendship WHERE receiver = '" .
$_SESSION["logged"] . "' AND sender = '" . $_GET['accept'] . "' OR receiver = '" .
$_GET['accept'] . "' AND sender = '" . $_SESSION["logged"] . "' "); // this line of
59

code deletes the friend request from the table friendship once the login user has
accepted the person as friend so that you the login user will not have any friend
request pending from the person that since they are now friends.
{
echo "<script type=\"text/javascript\">
alert(\"friend added\");
window.location='home.php';
</script>";
}
?>

reject_friend.php
The below script delete the friend request which the login user has.
<?php
include("connection.php"); ///This connects the script to the database.
include("home.php"); ///This get or collects the id (member_id) from the
database.

$myfriend=$_GET['delete'];
$me= $_SESSION["logged"];
60

$query = mysql_query("delete from myfriends WHERE myid = '" .


$_SESSION["logged"] . "' AND myfriends = '" . $_GET['delete'] . "' OR myid = '"
. $_GET['delete'] . "' AND myfriends = '" . $_SESSION["logged"] . "' ");
{
echo "<script type=\"text/javascript\">
alert(\"friend has been deleted\");
window.location='friends.php';
</script>";
}
?>

This part shows the login user those who are his/her friends.

61

This script shows the login user those who are his/her friends. The friends of the
login user will be shown by the php script below.
<?php
$member_id=$_SESSION["logged"]; // this is the login user id (member_id) that
has been assign with the variable $member_id.
$post = mysql_query("SELECT * FROM myfriends WHERE myid =
'$member_id' OR myfriends = '$member_id' ")or die(mysql_error()); // this line of
code selects the login user id (member_id) from the table name myfriends to show
those who are his or her friend.
$num_rows =mysql_numrows($post);
if ($num_rows != 0 )
{
while($row = mysql_fetch_array($post))
{
$myfriend = $row['myid'];
$member_id=$_SESSION["logged"];
62

if($myfriend == $member_id)
{
$myfriend1 = $row['myfriends'];
$friends = mysql_query("SELECT * FROM member WHERE member_id =
'$myfriend1'")or die(mysql_error());
$friendsa = mysql_fetch_array($friends);
echo '<a href=friendinfo.php?amifo='.$friendsa["member_id"].'
style=""><br>&nbsp;<img src="uploads/'. $friendsa['profile_picture'].'"
height="40" width="40"><br>&nbsp;'.$friendsa['firstname'].' '.
$friendsa['secondname'].' </a>';
}else{
$friends = mysql_query("SELECT * FROM member WHERE member_id =
'$myfriend'")or die(mysql_error());
$friendsa = mysql_fetch_array($friends);
echo '<a href=friendinfo.php?amifo='.$friendsa["member_id"].'>
<img src="uploads/'. $friendsa['profile_picture'].'" height="40"
width="40"><br>'.$friendsa['firstname'].' '.$friendsa['secondname'].' </a>';
}
}
}else{

63

echo 'You don\'t have friends </li>';


}
?>

This part teaches you how to post on your timeline and it will be seen by
those who are your friends, where they can comment on what you posted.

At this stage, when the login user posts any message, it will be seen by his/her
friends and what the login user friends also post, he/she will be able to see it too.
The login user can share anything with your friends via texts or messages.
To begin, we have to write a code that will allow the login user to post message
only to those who are his/her friends. This code is very complicated but very
64

simple to understand if you have been following these tutorials from the beginning.
It involved the MYSQL UNION, JOIN, INNER attributes.

Below is the form that you will submit your post (message).

<form action="home.php" METHOD="POST"


onsubmit="return(validate())" name="post_comment">
<div class="UIComposer_Box">
<textarea id="watermark" class="input" placeholder="Comment ."
style="color:#777;background-color:#fff;

overflow: hidden;

margin:6px 0px 0px 10px;" name="commenttext" ></textarea>


</div>
<input type="submit" name="submit_post" value="Post" id="post_button">
</form>

Next is the php script that allows the login user to post only to his/her friends
and also allows the login user to see what his/her friends have posted.

65

<?php
$member_id=$_SESSION["logged"];
$post = mysql_query("SELECT * FROM myfriends WHERE myid =
'$member_id' OR myfriends = '$member_id' ")or die(mysql_error());
$num_rows =mysql_numrows($post); //this line select those who are your friends
where when you post the can see it.
if ($num_rows != 0 ){
while($row = mysql_fetch_array($post)){
$myfriend = $row['myid'];
$myfriend1 = $row['myfriends'];
if($myfriend == $member_id){
}else{
$myfriend1 = $member_id;
}
Below is the script that selects your post and your friends post from the table post
that contains the post messages. It selects the post of only those who are your
friends and shows them to you.
$post=mysql_query("SELECT post.me, post.post_id, post.commenttext
FROM post INNER JOIN member ON post.me = member.member_id
WHERE post.me IN (SELECT myfriends FROM myfriends
66

INNER JOIN member ON (myid = member.member_id)


WHERE myfriends = $myfriend OR myid='$member_id'
UNION
SELECT myid FROM myfriends INNER JOIN member ON (myfriends =
member.member_id) WHERE myid = $myfriend1 OR myfriends = $member_id
UNION SELECT me FROM post WHERE me = '$myfriend1' OR
me=$myfriend ) ORDER BY post.date DESC"); /// This line of code selects your
friend post and your post from the database where you can see their post they can
see your post as well.
while($row = mysql_fetch_array($post)){
$member=$row["me"]; //This is login user id(member_id) from the post table in
the database.
$id=$row["post_id"]; // This is the post id(post_id) taking from the post table in the
database. This id will be used to show comment related to the post.

$user=mysql_query("SELECT * FROM member


WHERE member_id='$member'");
$roww = mysql_fetch_array($user);
/* div for posting and commenting*/
echo"<div id='comment_Container'>";

67

/* div commenting*/
echo'<div id="comment_body" >';
/* area showing posting messages*/
echo'<img src="uploads/'.$roww['profile_picture'].'" alt="" height="70"
width="70" style="position:absolute; margin:-56px 0px 0px 3px;"
border="1px"/>'; echo'<p style="color:blue; position:absolute; margin:61px 0px 0px 80px; font-size:19px;">'.
$roww["firstname"].'&nbsp;'.$roww["secondname"].'&nbsp;&nbsp;&nb
sp; </p>';

echo'<p style="color:#000000; margin:18px 0px 0px 10px;

">'.$row["commenttext"].'</p>';
echo'</div>';

68

Post comment related to a post

69

Now that the login user had seen the post of his/her friends, you might like to
add a comment to your friends post. The script below teaches you how to add a
comment related to the post above. This script is a continuation of the above script
of how to post on user timeline. If you like you can copy this script just beneath the
above echo`</div>`; or you can eliminate this text written in blue color and the
picture just above to allow the continuation of the post and show comments related
to post script.

$comment = mysql_query("SELECT * FROM postcomments WHERE


postid='$id' ORDER BY date DESC"); // this line select from the table called
postcomments where all the subcomments are stored. postid='$id' the postid is the
subcomment id and the `$id` is the id of the post that is related to the subcomment.
while($rows = mysql_fetch_array($comment)){
$commentid=$rows["memberid"];
$postt=mysql_query("SELECT * FROM member WHERE
member_id='$commentid'");
$rowwd = mysql_fetch_array($postt);
/* area showing comment on each post*/
echo'<img src="uploads/'.$rowwd['profile_picture'].'" alt=""
height="40" width="40" style=" margin:13px 0px 0px 3px;"

70

border="1px"/>'; echo'<p style="color:blue; margin:-45px 0px 0px 55px; fontsize:20px;">'.$rowwd["firstname"].'


'.$rowwd["secondname"].'</p>';
echo'<div style="position:relative; overflow: visible; margin:5px 0px
0px 57px;">'.$rows["comment"].':<span style="color:red;">
'.$rows["date"].'.</span></div>';
echo'<hr>';

Below is the form that you insert the subcomment or comment into subcomment
database table or you can eliminate this text in blue color to allow the continuation
of the post and show comments related to post script..
/* form for adding comment*/
echo'<form action="home.php" name="myForm" METHOD="POST"
onsubmit="return validateForm()">';
echo'<img src="uploads/'.$rowww['profile_picture'].'" alt="" height="40"
width="40" style="margin:8px 0px 0px 3px;" />';
echo'<input type="text" name="comment" placeholder="Add comment"
id="add_comment_field">';
echo'<input type="hidden" value=" '.$row['post_id'].'" name="postid">';
echo'<input type="submit" name="submit_comment" value="send"
id="comment_button">';
71

echo'</form>';
echo"</div><br>";

}
}
}
?>

Sending private messages


This section is to show you how the login user can send provide message to
only one user. This message will not be seen by unintended person you do not want
to see the message. We will need to use the friendinfo.php page above where we
are going to add the private message form.
//This is the database that we are using for this script.
CREATE TABLE IF NOT EXISTS `messages` (
`messageid` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` varchar(5000) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`postcommentid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=56 ;

72

<form action="message.php" method="post" onsubmit="return(validate())"


name="message"style="margin:20px 0px 0px 550px; color:red;">
<input type="text" name="messageform" size="49" style="height:30;class="reg">
<input type="hidden" value="<?php echo $row['member_id'];?>"
name="receiver"> //the $row['member_id']; above is the id (member_id) of the
user that the login user is sending the message.
<input type="hidden" value="<?php echo $roww['member_id'];?>"
name="sender"> //the $roww ['member_id']; above is the id (member_id) of the
login user who is sending the message.
<input type="submit" value="send">
</form>

Message.php
//Below is the message.php file that submits the message that the login user
submit into the database table called messages.
<?php
include("connection.php");
require_once("function.php");
$sendcomment=$_POST['message']; //this is the message that will be send to the
database.

73

$sender= $_POST["sender"];// this is the person that send the message id


(member_id) that will be stored in the database to identify the sender.
$receiver=$_POST['receiver']; // this is the person that receive the message id
(member_id) that will be stored in the database to identify the sender.
$query=mysql_query("INSERT INTO
messages(sender_id,date,receiver_id,message)
VALUES('$sender',NOW(),'$receiver','$sendcomment') ") or
die(mysql_error());
{
echo "<script type=\"text/javascript\">
alert(\"message added\");
window.location='messages.php'; // this takes you to the messages.php where you
will then see all the messages you have sent to someone.
</script>";
}
?>

74

How to see the messages login user has sent in php

Next after you have sent the message, you now have to see the message that
you have sent to someone. Below is the php script that collects the message from
the database. To get start create a page that is called messages.php where the user
you can see all your messages. At your home page create a link that will take you
75

to the messages.php. At the top of the messages.php page before the doctype
element insert this code.
//This is the database use for this script to send and receive messages.
CREATE TABLE IF NOT EXISTS `messages` (
`messageid` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` varchar(5000) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`postcommentid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=56 ;

<?php
session_start();
include("connection.php");
include("function.php");
include("insert.php"); // this is the file that insert the message into the database.
?>
Now in-between the <body></body> insert this code to collects the messages
from the database with the table name messages.
<?php
//Section for your massages
76

$member_id=$_SESSION["logged"];
$query = mysql_query("SELECT * FROM messages WHERE
sender_id = '$member_id'");
if(mysql_num_rows($query) > 0) // this line of code selects the message from the
table name messages of the login user.
{
while($row = mysql_fetch_array($query))
{
$_query = mysql_query("SELECT * FROM member WHERE
member_id = '" . $row["sender_id"] . "'");
while($_row = mysql_fetch_array($_query))
{
echo '
<div id="messages_div">

<div style="margin:5px 0px 0px 87px; color:blue;" >


'.$_row['firstname']." ".$_row['secondname'].'</div>
<img src="uploads/'.$_row['profile_picture'].'" alt="" height="70" width="70"
style=" margin:-17px 0px 0px 7px;" />
<div style="margin:-1px 0px 0px 7px;">'.$row['message'].'</div>
77

</div>
';
}
}

}else{
echo"<div id='messages_div'>";
echo 'You have not sent any message';
echo"</div>";
}
?>
How to see the messages someone sent to you in php

78

Now, after you have seen how to view the messages you have sent to someone.
Now we look forward to see how to view the message (s) that someone have sent
to you. Take note that this script is place on the same page (messages.php) where
you saw how to view the messages you send. You just need to add the below script
to the (messages.php) page which is just above. Do not create another page for it.
//This is the table of the database use for sending and receiving messages.
CREATE TABLE IF NOT EXISTS `messages` (
`messageid` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` varchar(5000) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`postcommentid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=56 ;

<?php
//Section for showing those who has message the login user
$member_id=$_SESSION["logged"]; //this is login user id(member_id) collected
from the database.
$query = mysql_query("SELECT * FROM messages WHERE
receiver_id='$member_id' "); //this line of code select from the table name
messages where the value receiver store the login user id (member_id) that will be

79

used to show the login user any message that he/she has received from someone
else.
if(mysql_num_rows($query) > 0)
while($row = mysql_fetch_array($query))
{
$sender=$row['sender_id']; //this line of code collect the id (member_id) of the
person that have sent the login user a message and it assigned to the variable
$sender.
$_query = mysql_query("SELECT * FROM member WHERE
member_id = '$sender' ");// this line of code will select the information such as
firstname and second of those who have sent the login user a message from the
table member only when the member_id equals $sender.
while($_row = mysql_fetch_array($_query))
{
echo '
<div id="messages_see">
<div style="margin:5px 0px 0px 87px; color:blue;"
>'.$_row['firstname']." ".$_row['secondname'].'</div> //show the names of the
person that has sent the login user a message
<img src="uploads/'.$_row['profile_picture'].'" alt="" height="70"
width="70" style=" margin:-17px 0px 0px 7px;" />
80

<div style="margin:1px 0px 0px 7px; ">'.$row['message'].'


&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<pan style="color:red;"s> '.$row['date'].'</span></div>
</div>
';
}
}

}else{
echo"<div id='messages_div'>";
echo 'No one has send you a message';
echo"</div>";
}
?>

81

LOGOUT
The final stage of this tutorial is the logout script. The logout script enables the
login user to signout from the social network forum. Below is the link button that
when the login user clicks, it will take him/her to the index.php page where he/she
may login to access he/her account.
<a href="logout.php"><button id="logout">Logout</button></a>

Logout.php
Below is the logout.php file. This is the file that when the login user click the
link above it will take him to the index.php page the session of the user will be
destroyed.
<?php
session_start();session_destroy();header("location: index.php");
?>

82

Thanks for using our ebook. We hope that this book has helped you to
understand the tutorial on how to create a social network forum in php and
JavaScript. We are 24 hours available to answer any question or doubt you
concerning this programming ebook. We response to your question as fast as we
can and possible.
To those who have purchased this ebook the can have the code for free via the
emails we will provide below. If you need the all codes for this tutorial you can
email us to send you the code which we have used in this tutorial for you to better
understand the tutorial. The code will be in window compress format or winrar.
This ebook is our first edition on how to create a social network forum in php
and JavaScript. We are working on the second edition which will contain many
features like viewing those who are online, like and unlike features, posting
messages and photos on your timeline, editing account, convert user first and
second name into Capital letter and many more. It will be released on the 20th
April, 2016. We are also currently working on a tutorial on how to create your own
twitter. The ebook of the twitter tutorial will be released on 17th March, 2016. You
can have your own copy which will help you to better understand coding
techniques and tricks in php and JavaScript.
Contact us for any inquires questions or doubt you have concerning this tutorial
via the emails below.

Email: easygoing@gmail.com or easygoing@yahoo.com

83

You might also like