الاثنين، 15 أكتوبر 2012

Discussion Forum PHP and MYSQL


Download

Today we will learn  how to create a simple discussion forum using PHP and MYSQL. This project is big and can't be covered in single post,so I would divide it into four different posts. Today we will discuss about how we can create skeleton of this project.Next week, we will see how we can use advance features such as jquery,ajax,functions and classes with this project.

File Structure:
We will create five files in root folder and one file db.php (Database configuration file) inside config folder.
index.php : This is home_page or our site from where user can sign in
sign_up.php:  Its for new users registration
discuss.php: Post topics
reply.php : Post replies
log_out.php:log out user


Tools: Apache, PHP and Mysql (Download Xampp or WAMP)

What we are trying to do?

When we think about discussion forum, we know that we will need one login system and only registered can post and reply inside the forum.So, we will create three pages just for user login and they are index.php(login form), sign_up.php(for registering new users) and log_out.php(to remove session).

Other two pages will be used for discussion;first for submitting topic and other one will be used for replying.


Step 1. Create Databases:

I have created database discussion where we will create four tables:
  • categories
  • users
  • topics
  • replies
Database: `discussion`

----------------------------------------------------------

--
-- Table structure for table `categories`
--

CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(11) NOT NULL auto_increment,
`category_name` varchar(100) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`category_id`)
ENGINE=MyISAM 
DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `replies`
--

CREATE TABLE IF NOT EXISTS `replies` (
  `reply_id` int(11) NOT NULL auto_increment,
 `reply_content` text collate latin1_general_ci NOT NULL,
  `topic_id` int(11) NOT NULL,
  `reply_user_id` int(11) NOT NULL,
  PRIMARY KEY  (`reply_id`)
) ENGINE=MyISAM 
DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `topics`
--

CREATE TABLE IF NOT EXISTS `topics` (
`topic_id` int(11) NOT NULL auto_increment,
`topic_content` text collate latin1_general_ci NOT NULL,
`category_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 
COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL auto_increment,
`user_name` varchar(16) collate latin1_general_ci NOT NULL,
`password` varchar(16) collate latin1_general_ci NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;


Step 2. Inserting some dummy DATA
Fill in the category table with related subjects or anythings related , I have filled it with physics,chemistry,maths,physics and biology:
INSERT INTO `discussion`.`categories` (`category_id`, `category_name`) 
VALUES (NULL, 'physics'), 
(NULL, 'chemistry'), 
(NULL, 'maths'), 
(NULL, 'physics'), 
(NULL, 'biology');
Create Admin user with username and password admin:
INSERT INTO `discussion`.`users` (`user_id`, `user_name`, `password`) VALUES ('1', 'admin', 'admin');
Step 2. Coding Each and very project

index.php
<?php session_start(); 
if(isset($_POST['submit'])) {
include('./config/db.php');
$user_name = $_POST['user_name'];
$password = $_POST['password'];
$user_name = stripslashes($user_name);
$password = stripslashes($password);
$user_name = mysql_real_escape_string($user_name);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM `users` 
WHERE user_name='$user_name' and 
password='$password'";
$result=mysql_query($sql); // execute query

// mysql_num_row is a function used to count number of results we get from the above query
$count=mysql_num_rows($result);

// If result matched $user_name and $password, table row must be 1 row
if($count==1){
$sql="SELECT user_id FROM `users` WHERE user_name='$user_name'";
$result=mysql_query($sql); // execute query
$user_id_array = mysql_fetch_array($result);
$user_id = $user_id_array['user_id'];
// Register $user_name and $user_id and redirect to file "discuss.php"
$_SESSION['user_name'] = $user_name;
$_SESSION['user_id'] = $user_id;
header("location:discuss.php");
}
else {
echo "Please enter correct username and password (check whether capslock is on)";
}

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD 
XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Discussion forum from iprojectideas.blogspot.com</title>
</head>

<body>

<form action="#" method="post" name="topic_form">
<label>Username</label><br /> <input name="user_name" type="text" />
<br />
<label>Password</label><br />
<input name="password" type="text" /><br />
<input name="submit" type="submit" value="submit" />

</form>
<p>New Users <a href="sign_up.php">Sign up now</a></p>

</body>
</html>

sign_up.php
 <?php session_start(); 
if(isset($_POST['submit'])) {
include('./config/db.php');
$user_name = $_POST['user_name'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$user_name = stripslashes($user_name);
$password = stripslashes($password);
$repassword = stripslashes($repassword);
$user_name = mysql_real_escape_string($user_name);
$password = mysql_real_escape_string($password);
$repassword = mysql_real_escape_string($repassword);
// check for errors
if($user_name == '' || $password == '' || $repassword =='') {
echo "Please fill correct username and password";
}
else if($password != $repassword) {
echo "password does not match , please try again";
}

else {
$sql="SELECT * FROM `users` WHERE user_name='$user_name'";
$result=mysql_query($sql); // execute query

// mysql_num_row is a function used to count number of results we get from the above query
$count=mysql_num_rows($result);

// if user name does not exist than register this user in our database and redirect him to discussion forum
if($count==1){
echo "User name has been already taken, please try again!";
}
else {
$sql = "INSERT INTO `discussion`.`users` (`user_id`, `user_name`, `password`) VALUES (NULL, '$user_name', '$password');";
$result=mysql_query($sql); // execute query
if($result) {

// Register $user_name,$user_id and redirect to file "discuss.php"
// find out user id
$sql="SELECT user_id FROM `users` WHERE user_name='$user_name'";
$result=mysql_query($sql); // execute query
$user_id_array = mysql_fetch_array($result);
$user_id = $user_id_array['user_id'];
$_SESSION['user_name'] = $user_name;
$_SESSION['user_id'] = $user_id;
header("location:discuss.php");
}
else {
echo "Error, please try again";
}
} // end of inner else

} // end of outer else
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Sign up | Discussion forum from iprojectideas.blogspot.com</title>
</head>

<body>

<form action="#" method="post" name="topic_form">
<label>Username</label><br /> <input name="user_name" type="text" />
<br />
<label>Password</label><br />
<input name="password" type="text" /><br />
<label>Re-enter Password</label><br /><input name="repassword" type="text" /><br />
<input name="submit" type="submit" value="submit" />

</form>
<p>Already Registered <a href="index.php">Sign in</a></p>

</body>
</html>

discuss.php
<?php 
session_start();
if(!isset($_SESSION['user_name'])) {
header("location:index.php");
}
else {
$user_name = $_SESSION["user_name"];
$user_id = $_SESSION["user_id"];
echo "Welcome $user_name ";
echo "<a href=\"log_out.php\">Log out</a>";
include('./config/db.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Discussion forum from iprojectideas.blogspot.com</title>
</head>

<body>
<?php if(isset($_POST['topic'])) {
$topic = $_POST['topic'];
$category_id = $_POST['category_id'];
$sql = "INSERT INTO `discussion`.`topics` (`topic_id`, `topic_content`, `category_id`, `user_id`) VALUES ('', '$topic', '$category_id', '$user_id');";
$rsd = mysql_query($sql);
echo "Thanks for submitting your topic $topic in $category_id ";

}
else {
?>
<form action="#" method="post" name="topic_form">
<label>Topic</label><br /> <textarea name="topic" cols="100" rows="5"></textarea><br />
<label>Category</label>
<select name="category_id">
<?php $sql = "SELECT * FROM `categories`;";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$category_id = $rs['category_id'];
$category_name = $rs['category_name'];

echo "<option value=\"$category_id\">$category_name</option>";
}
?>
</select><br />
<input name="submit" type="submit" value="submit" />

</form>
<?php }
echo"<h3>Submitted Topics:</h3>";
$sql = "SELECT * FROM `topics` ORDER BY `topics`.`topic_id` DESC;";
$topics = mysql_query($sql);
while ($row = mysql_fetch_array($topics, MYSQL_ASSOC )){
$topic_content = $row['topic_content'];
$topic_id = $row['topic_id'];
echo "<h3>$topic_content</h3>";
$sql = "SELECT * FROM `replies` where `replies`.`topic_id` = $topic_id;";
$replies = mysql_query($sql);
while($row = mysql_fetch_array($replies, MYSQL_ASSOC )) {
$reply_content = $row['reply_content'];
echo "<p> $reply_content</p>";
} // end of while
echo "<br /><a href=\"reply.php?topic_id=$topic_id\">reply</a><br />";
}

?>
</body>
</html>

reply.php
<?php 
session_start();
if(!isset($_SESSION['user_name'])) {
header("location:index.php");
}
else {
$user_name = $_SESSION["user_name"];
$user_id = $_SESSION["user_id"];
echo "Welcome $user_name ";
echo "<a href=\"log_out.php\">Log out</a>";
include('./config/db.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Discussion forum from iprojectideas.blogspot.com</title>
</head>

<body>
<?php if(isset($_POST['reply'])) {
$reply = $_POST['reply'];
$topic_id = $_POST['topic_id'];

$sql = "INSERT INTO `discussion`.`replies` (`reply_id`, `reply_content`, `topic_id`, `reply_user_id`) VALUES (NULL, '$reply', '$topic_id', '$user_id');";
$rsd = mysql_query($sql);
if($rsd) {
echo "Thanks for submitting your reply $reply. <a href=\"discuss.php\">Return Back</a> to view it. "; }
else {
echo "Error, reply submission fail";
}

}
else {
$topic_id = $_GET['topic_id'];
$topic_id= stripslashes($topic_id);
$topic_id = mysql_real_escape_string($topic_id);
echo"<h3>Reply:</h3>";
$sql = "SELECT * FROM `topics` where `topics`.`topic_id` = $topic_id;";
$topics = mysql_query($sql);
$row = mysql_fetch_array($topics, MYSQL_ASSOC );
$topic_content = $row['topic_content'];

echo "<h3>$topic_content</h3>"; ?>
<form action="#" method="post" name="reply_form">
<label>Reply</label><br />
<textarea name="reply" cols="100" rows="5"></textarea><br />
<input type="hidden" name="topic_id" value="<?php echo"$topic_id" ?>" />
<input name="submit" type="submit" value="reply" />
</form>
<?php }
?>
</body>
</html>

log_out.php
<?php 
session_start();
if(!isset($_SESSION['user_name'])) {
header("location:index.php");
}
else {
session_destroy();
header("location:index.php");
}
?>

 config/db.php
<?php 
$db_host='localhost';
$db_database='discussion';
$db_username='YOUR_DB_USERNAME';
$db_password='YOUR_DB_PASSWORD';
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection){ die("Could not connect to the database: <br />". mysql_error( )); }
// Select the database
$db_select = mysql_select_db($db_database); if (!$db_select){
die ("Could not select the database: <br />". mysql_error( )); }


?>

Download

ليست هناك تعليقات:

إرسال تعليق