Académique Documents
Professionnel Documents
Culture Documents
ideas and tricks you will obtain from this EBook as you follow the tutorial in this
EBooks.
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:
Chapter Three:
Chapter Four:
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
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
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"])) {
10
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.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 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.
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();
}
}
}
?>
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);
}
//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);
$_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
<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`='".
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
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
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
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
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. */
37
Else
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.
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>
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.
}
?>
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>
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
47
}
?>
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.
*/
(member_id)
</head>
<?php
$post = mysql_query("SELECT * FROM member WHERE
member_id = '$friend1' OR member_id = '$friend1'")or
die(mysql_error());
First a table is created called friendship in the database. This is how the table
looks like:
50
<?php
$result= mysql_query("select * FROM `member` WHERE `email`!='".
$_SESSION["SESS_FIRST_NAME"]."' LIMIT 10");
while($row=mysql_fetch_array($result))
{
echo '
51
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>";
}
}
}
?>
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
56
57
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
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> <img src="uploads/'. $friendsa['profile_picture'].'"
height="40" width="40"><br> '.$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
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).
overflow: hidden;
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
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"].' '.$roww["secondname"].' &nb
sp; </p>';
">'.$row["commenttext"].'</p>';
echo'</div>';
68
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.
70
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>";
}
}
}
?>
72
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
74
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>
';
}
}
}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
}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.
83