Make Chat Room In Php & Mysql

We can make custom group Chat room in php without using any extension, library or api. We will make it with core php and simply javascript. Yes you are right! we are going to do this. First of all you need to have some some core php and javascript skills database as well. It’s quite easy to make in half hour. Let’s make it.

Database:

First we need to make a database where we will store all the information regarding the users registration and their chats only. We are having three simple tables chat , country and user that’s all we have in our database. I’m showing the hierarchy of these tables with the columns below.

chat Table
– – – – – – – – – – – – – – – – – – – – – – – – – – – – –
chat_id | chat_person_name | chat_value | chat_time
0 | john | hello | 17:01:24
1 | martin | hi | 17:03:24
2 | tom | fine | 17:05:24
3 | carter | good | 17:07:24
– – – – – – – – – – – – – – – – – – – – – – – – – – – – –

user Table
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
user_id | user_name | user_email | user_password | user_country | user_status
0 | john | john@xyz.com | 12345 | canada | 1
1 | martin | john@xyz.com | 12345 | us | 0
2 | tom | john@xyz.com | 12345 | london | 1
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

We are having two status types. 0 and 1 if the status of a user is 0 means he is offline and 1 means he is online now.

country Table
– – – – – – – – – – – – –
country_id | country_name
0 | Austrailia
1 | America
2 | India
– – – – – – – – – – – – –

You can get the mysql query script below to make these tables on your side.

-- --------------------------------------------------------
-- Host:                         127.0.0.1
-- Server version:               5.6.25 - MySQL Community Server (GPL)
-- Server OS:                    Win32
-- HeidiSQL Version:             9.3.0.5045
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;


-- Dumping database structure for ajaxdb
CREATE DATABASE IF NOT EXISTS `ajaxdb` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `ajaxdb`;

-- Dumping structure for table ajaxdb.chat
CREATE TABLE IF NOT EXISTS `chat` (
  `chat_id` int(11) NOT NULL AUTO_INCREMENT,
  `chat_person_name` varchar(100) NOT NULL,
  `chat_value` varchar(100) NOT NULL,
  `chat_time` time DEFAULT NULL,
  PRIMARY KEY (`chat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table ajaxdb.chat: ~0 rows (approximately)
/*!40000 ALTER TABLE `chat` DISABLE KEYS */;
/*!40000 ALTER TABLE `chat` ENABLE KEYS */;

-- Dumping structure for table ajaxdb.country
CREATE TABLE IF NOT EXISTS `country` (
  `country_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(100) NOT NULL,
  PRIMARY KEY (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

-- Dumping data for table ajaxdb.country: ~0 rows (approximately)
/*!40000 ALTER TABLE `country` DISABLE KEYS */;
REPLACE INTO `country` (`country_id`, `country_name`) VALUES
	(1, 'India'),
	(2, 'America'),
	(3, 'Canada');
/*!40000 ALTER TABLE `country` ENABLE KEYS */;

-- Dumping structure for table ajaxdb.user
CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `user_password` varchar(100) NOT NULL,
  `user_country` varchar(100) NOT NULL,
  `user_status` varchar(100) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `UX_Constraint` (`user_email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table ajaxdb.user: ~0 rows (approximately)
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
/*!40000 ALTER TABLE `user` ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

That’s all we have completed our database side now we will move on to make php files so that we can chat in a group live.

config.php

This file will contain our database connection details.

<?php
  $conn = mysqli_connect('localhost' , 'root' , '', 'ajaxdb')or die ('problem to connect database');
?>

practice.php

We will first make a practice.php file in which we will have our registration form and as well as login form. I’ve write both of these modules in a single file so that our code will be short and we will have less number of files at the end. Follow the code below. As you can see below we have write some javascript functions to validate email and password. So that a person who is already registered with an email he will not be able to use this email again in our chat room. And you know password and confirm password should be same so that member know what he is writing in the password field so that he will remember his password easily.

<script>
function getcity(id) {
			xhr = new XMLHttpRequest();
			xhr.open('GET' , 'test.php?idd='+id, true);
			xhr.send();
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4 && xhr.status==200){
					document.getElementById("city_display").innerHTML = xhr.responseText;
					}
			
				}


}

function getEmail(emailid){

			email  = new XMLHttpRequest();
			email.open('GET' , 'test2.php?email='+emailid, true);
			email.send();
			email.onreadystatechange = function(){
				if (email.readyState == 4 && email.status == 200)
				{
					
					document.getElementById('emailDiv').innerHTML = email.responseText;
					}
				
				}
	
	
	}
	
	
	function password (pass){
	var a =	document.getElementById('pass1').value;
	//	document.write(a);
		var b = document.getElementById('pass2').value;
		if (a == b ){
			document.getElementById('cnfrmpass').innerHTML = "<font color='#00CC00'>Matched</font>";
			}
			else {
				
				document.getElementById('cnfrmpass').innerHTML = "<font color='red'>Miss matched</font>";
				}
		}

</script>

<?php
include_once('config.php');
$result = mysqli_query($conn, 'select * from country');
if (!$result) {
    echo 'query failed';
}
?>


<?php
if (isset($_GET['logout_successfully'])) {
?><?php
    echo $_GET['logout_successfully'];
?>
<?php
}
?>
<table><tr>
<td colspan="2"><center><h1>Registeration</h1></td></tr><tr>
<form method="post" action="insert.php">
<td>Name : </td><td><input type="text" name="name" /></td></tr><tr>
<td>Email : </td><td><input type="email" name="email" onBlur="getEmail(this.value)" /></td><td><div id="emailDiv"></div></td>
</tr><tr>



<td>country : </td><td><select name="country">
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php
    echo $row['country_id'];
?>"> <?php
    echo $row['country_name'];
?>
</option>

<?php
}
?>
</select></td><td><div id="city_display"></div>
</td></tr><tr>

<td>Password : </td><td><input type="password" name="pass1" id="pass1"/></td></tr><tr><br />
<td>Confirm Password : </td><td><input type="password" name="pass2" id="pass2" onblur="password()" /></td><td>
<div id="cnfrmpass"></div></td></tr><tr>
<td colspan="2"><center><input type="submit" name="sbt" /></td></table></form> <br /><br />
<?php
if (isset($_GET['registeration_successfull'])) {
?><?php
    echo $_GET['registeration_successfull'];
?>
<?php
}
?>



<form method="post" action="process.php">
<table><tr>
<td colspan="2"><center> <h1>Login</h1></td>
</tr>

<tr>
<td>
Email : </td><td><input type="text" name="email"  /></td></tr><tr>
<td> Password : </td><td><input type="password" name="password" /></td></tr>
<tr><td colspan="2"><center> <input type="submit" name="loginbtn" /></td></tr></table>
<?php
if (isset($_GET['login_error'])) {
?><?php
    echo $_GET['login_error'];
?>
<?php
}
?>
</form> 

test2.php

When user gives his email in our registration form then email validation works that this email is present in our system or not. So ajax call made from the practice.php file to this file to validate the email and it returns some status to show user that his email is already registered or not.

<?php
$email = $_GET['email'];
//echo $email;
include_once('config.php');
$result = mysqli_query ($conn , "SELECT * FROM ajaxdb.user WHERE user_email = '".$email."'");
$rows = mysqli_num_rows($result);
//echo $rows;
if($rows > 0 )
{
	echo "<font color='#FF0000'>email already exists</font>";

}
else {
	echo "<font color='#00CC00'>email available</font>";

	} ?>

insert.php

Right after we will make insert.php file. So that when a user will register in chat room all his information will go on insert.php file and this file insert the information in to our database.

<?php
$name     = $_POST['name'];
$email    = $_POST['email'];
$country  = $_POST['country'];
$password = $_POST['pass1'];

include_once('config.php');
$result = mysqli_query($conn, "INSERT INTO `ajaxdb`.`user`
            (`user_id`,
             `user_name`,
             `user_email`,
             `user_password`,
             `user_country`,
             `user_status`)
VALUES (NULL,
        '$name',
        '$email',
        '$password',
        '$country',
        '0');");
if ($result) {
    header('location: practice.php?registeration_successfull=<span style="color:green">You have successfully registered. You can now login.</span>');
} else {
    echo "failed";
}

?>

Right now we have completed all the steps that works to register a user in our chat room. Now we are going to work on the login module. And off course as I’ve already mentioned that our login module is present in the practice.php after successful registration you will automatically redirected to the practice.php file so that you can login from it.

process.php

This file will work for the login module. When a member try to login he will be redirected to this file with his login details and then this file will check the user is exist in our database or not. If his credentials will be right then he will be welcomed in the chat room.

<?php
session_start();
include_once('config.php');
$email = $_POST['email'];
$password = $_POST['password'];
$result = mysqli_query($conn , "select * from user where user_email='$email' and user_password='$password'");
	
	while($row = mysqli_fetch_assoc($result))
	{
		$name = $row['user_name'];
	}
	
	if(mysqli_num_rows($result)>0)
	{
		echo "success";
		$_SESSION['email'] = $email;
		$_SESSION['password'] = $password;
		$_SESSION['name'] = $name;
		$query = mysqli_query($conn,"UPDATE user
		SET user_status = '1' WHERE
		user_email = '$email';");
		header('location: chatroom.php');
	}
	else
	{
		echo "failed";
		header('location: practice.php?login_error=<span style="color:red">Username or password is wrong</span>');
	}	
?>

chatroom.php

This is our main file in which all the members will chat in a group chat. After successful login process you will be redirected to this file and this file will show layout of three section in which section one will show all the chats that is done by all the members, second section will show the current users that are online or offline and third section will be text area in which you will write some message to chat with others.

chat room

chat room

<?php
session_start();
 ?>
<script>
	
function getText() {
		
	var $a = document.getElementById('text').value;
	
	xhr = new XMLHttpRequest();
	xhr.open('POST' , 'chatdb.php',true);
	xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
	xhr.send('chat='+$a);
	xhr.onreadystatechange=function(){
		if (xhr.responseText)
		{
		//	document.getElementById('chatarea').innerHTML=xhr.responseText;
		}
	}
}
		

function setText(){
	
	xhr = new XMLHttpRequest();
	xhr.open('POST' , 'chatFetch.php' , true);
	xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
	xhr.send();
	xhr.onreadystatechange = function()
	{
		document.getElementById('chatarea').innerHTML = xhr.responseText;
	}
		
	}
	setInterval("setText()",2000);
	setInterval("users()",3000);

	
function users(){
	xhr1 = new XMLHttpRequest();
	xhr1.open('POST' , 'userFetch.php' , true);
	xhr1.setRequestHeader('content-type','application/x-www-form-urlencoded');
	xhr1.send();
	xhr1.onreadystatechange = function()
	{
		document.getElementById('loginperson').innerHTML = xhr1.responseText;
	}
}
		
		
</script>
<?php
include_once('config.php');
echo	$_SESSION['name'];

if (isset($_GET['logout']))
{
	$result = mysqli_query($conn, "UPDATE user
	SET user_status = '0'
	WHERE user_email = '$_SESSION[email]';");
	session_destroy();
	header('location: practice.php?logout_successfully=<span style="color:green">You have successfully Logged Out.</span>');
}
?>
<form action="">
	<input type="submit" name="logout" value="logout">
</form>
<div id="chatbox">
	
	<div id ="chatarea">
	</div>

	<div id="loginperson">
	</div>

	<div id="textbox">
	<form>
		<textarea rows="4" cols="100" id="text"></textarea>
		<input type="button" value="send"  onclick="getText()" />
	</form>
	</div></center>
</div>
<style>
#chatbox
{
	border:double;
	height:500px;
	width:1000px;
	align;
}
#chatarea 
{
	width:750px;
	height:400px;
	border:double;
	float:left;
	overflow:auto;
}
#loginperson 
{
	width:238px;
	height:497px;
	border:double;
	float:right;
}
#textbox 
{
	width:750px;
	height:89px;
	border:double;
	float:left;
}
#chatting 
{
	float:left;
}
</style>
<?php
	if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
		//session_destroy();
		header('location: practice.php');
		}
?>

In this file we have three ajax based javascript functions getText(), setText(), users(). These all functions have their own meaning. getText() function insert the chats of the current user in to the database. Second function setText() get all the chats from the start and display in the chat showing section. This function will be continously calls after some micro seconds so that we always have the new chats on our screen. Third function show all the users with their statuses so that you can see which user is offline and which one is online at this time.

chatdb.php

We are using this file to insert the chats when a member write some message and click on send button. This file will be used from the chatroom.php file. And chatroom.php file is ajax based so that we have make this file separately.

<?php
session_start();
include_once('config.php');
if(isset($_POST['chat']))
{
	$result = mysqli_query($conn , "INSERT INTO `ajaxdb`.`chat`
            (`chat_id`,
             `chat_person_name`,
             `chat_value`,
			 `chat_time`
			 )
VALUES (NULL,
        '$_SESSION[name]',
		'$_POST[chat]',
		NOW()
		);");
	
	}

?>

chatFetch.php

We were showing the live chat log in the chat room section it was the part of this file. All the new chats request will be completed from this file. This file will return all the new chats that we have in our database.

<?php
include_once('config.php');
$result= mysqli_query($conn , "SELECT * FROM chat");
while ($row = mysqli_fetch_assoc($result)){
	echo $row['chat_person_name']." :";
	echo $row['chat_value']."<br>";
	
	}
?>

userFetch.php

Live users users to see who is online or not , all these information will be sent from this file. An ajax based request will come on this file and it will give all the information about the users who are online or offline.

<?php
include_once('config.php');
$result= mysqli_query($conn , "SELECT * FROM user");
while ($row = mysqli_fetch_assoc($result)){
	if($row['user_status'] == 1 ){
		echo "<font color='#009900'>".$row['user_name']." (Online)"."</font><br>";
		}
		else {
				echo "<font color='#FF0000'>".$row['user_name']." (Offline)"."</font><br>";
			}
	}

?>

Finally our small chat system is now completed. Now you can use this system for group chat. If you face any type of problem to run this feel free to make comments we will resolve your issues. And off course make comments and write your feedback’s if you really like this post.
You can download all of this by click over here.

Download Zip