Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Simple Chatroom(part 1) (0 Comments)
Admin: Posted Date: March 3, 2010

Hey there few days ago I was talking with some girls in msn. ya know that sleek talk and suddenly this idea came to my head that I should make a jQuery chat. And I did it, Sugar Chat 1.0 this is little complicated version of this tutorial.

Simple Chatroom with PHP & jQuery

First let's make a database and create tables:

[highlight="sql"]
CREATE TABLE IF NOT EXISTS `auth` (
`user` varchar(30) NOT NULL,
`session` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
[/highlight]

[highlight="sql"]
CREATE TABLE IF NOT EXISTS `chat` (
`time` varchar(30) NOT NULL,
`user` varchar(30) NOT NULL,
`text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
[/highlight]

Let's add some style to our chatroom with this:

style.css

[highlight="css"]
body{

font-family: Verdana;
font-size: 11px;
background-color: #BFC08D;

}

.tablebottom{

border-bottom: 1px solid #E6E6E6;

}

.middlebox{

border-bottom: 1px solid #E6E6E6;
border-left: 1px solid #E6E6E6;

}

#maintable{

border: 1px solid #E6E6E6;
background-color: #C9CCBB;

}

#chatscreen{

width: 850px;
height: 500px;
float: left;
overflow: auto;
text-align: left;

}

#onlineusers{

height: 500px;
width: 100px;
float: right;

}

a{

text-decoration: none;
color: #000000;

}

a:hover{

text-decoration: none;
color: #8DBAEB;

}

input{

border: 1px solid #E6E6E6;

}

#submitbutton{

background-color: #FFFFFF;
font-family: Tahoma;

}

#messagebox{

background-color: #E8E9E2;

}

#userbox{

background-color: #E8E9E2;
height: 20px;

}

#usersbox{

text-align: left;
background-color: #E8E9E2;

}

.user{

border-bottom: 1px solid #969A7A;

}
[/highlight]



Now when it's done let's create our config file..

config.php
Code:


// Let's connect to our database
// Usually your host is 'localhost'
// But sometimes it might be different so ask your host
// About your database server address
$mysql_con mysql_connect("localhost""Username""Password");

// Now let's check if everything is good
// If there's something wrong.. let's display an error
if(!$mysql_con){
    
    die(
mysql_error());
  
}
// Let's select our database
$mysql_db mysql_select_db("DatabaseName"$mysql_con);

// Let's check here also is everything is okay
// If there's something wrong, let's display an error
if(!$mysql_con){
    
    die(
mysql_error());
    
}
?>
 Now our config file is ready, database has been set up and now are we ready to start creating our chat
First we need to download jQuery libary.
Let's create an "includes" folder and let's put it there.
Now let's create our functions file that will put everything to work..
actions.php

Code
?php

// Let's start our session
session_start();

// Include the config.php because we are
// Going to start work with our database
include("config.php");

// First let's make a login form
// Here user sets his/her username that
// He/she will use in this chatroom
function login_form(){
 
    echo 
"<br /><br />";
    echo 
"<table width='500' border='0' id='maintable' style='background-color: #F3F3F3' align='center'>"
        
."<tr>"
        
."<td align='center'><font style='font-size: 20px'>Login</font></td>"
        
."</tr>"
        
."<tr>"
        
."<td align='center'>";
    echo 
"<form action='index.php?act=login' method='post'>"
        
."Username: <input type='text' name='username' /> <input type='submit' id='button' value='Login' /><br /><br />"
        
."</form>";        
    echo 
"</td>"
        
."</tr>"
        
."</table>";

}

// Now let's log that user in
function process_login(){
    
    
// Let's get user's username
    
$username $_REQUEST['username'];
    
    
// Now let's find if there are records about him/her in database
    
$sql "SELECT * FROM auth WHERE user='".mysql_real_escape_string($username)."'";
    
$query mysql_query($sql);
    
    
// If there are any records, delete them
    
if(mysql_num_rows($query)>0){
        
        
$sql "DELETE FROM auth WHERE user='".mysql_real_escape_string($username)."'";
        
$query mysql_query($sql);
        
        
// Check that everything is okay
        // If something is wrong, display an error
        
if(!$query){
            
            die(
mysql_error());
            
        }
        
    }
    
    
// Now let's set session with user's name
    // And insert it into database so we know that
    // He/she is logged in
    
$_SESSION['user'] = $username;
    
$sql "INSERT INTO auth (user, session) VALUES ('".mysql_real_escape_string($username)."', '".session_id()."')";
    
$query mysql_query($sql);
    
    
// Check that all things went well
    // If something was wrong, display an error
    // But if evetrything is good, redirect him/her 
    // To the chatroom
    
if(!$query){
        
        echo 
"Can not insert info into database!
"
mysql_error();
        
    }else{
        
        
header("Location: index.php");
        
    }
    
}

// Now let's make a function that logs users our
function logout(){
    
    
// This will delete any traces of him/her
    // From database so it will be a clean sheet
    // When he/she comes back
    
$sql "DELETE FROM auth WHERE session='".mysql_real_escape_string(session_id())."'";
    
$query mysql_query($sql);
    
    
// Little error checking again
    
if(!$query){
        
        echo 
"Can not delete info from database!";
        
    }else{
        
        
// If everything went well, let's destroy
        // Session and redirect to main page also
        // Where login form waits him/her
        
session_destroy();
        
header("Location: index.php");
        
    }
    
}

// Now we want to show user's username
// In "Welcome [user]" area
function get_username(){
    
    
// Let's get all info abour our current session from database
    
$sql "SELECT * FROM auth WHERE session='".mysql_real_escape_string(session_id())."'";
    
$query mysql_query($sql);
    
$row mysql_fetch_array($query);
    
    
// If there aren't any records
    // Let's set our user's name to "Guest"
    // If there are records let's get the real username
    
if(mysql_num_rows($query) == "0"){
        
        
$username "Guest";
        
    }else{
        
        
$username $row['user'];
        
    }
    
    return 
$username;
    
}


// Now we want to display "Log In" or "Log Out"
// Link after greeting
function get_link(){
    
    
// Again we check for records from database
    
$sql "SELECT * FROM auth WHERE session='".mysql_real_escape_string(session_id())."'";
    
$query mysql_query($sql);
    
$row mysql_fetch_array($query);
    
    
// If there are no records about our user
    // Let's display "Log In" link
    // But if there are records about our user
    // Display a "Log Out" link
    
if(mysql_num_rows($query) == "0"){
        
        
$link "Login";
        
    }else{
        
        
$link "Logout";
        
    }
    
    return 
$link;    
    
}

// This is the function that posts
// User messages to database
function post_message(){
    
    
// Let's clean our text that user entered
    
$text addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));
    
    
// Now let's insert it into database
    
$sql "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."', '".get_username()."', '".$text."')";
    
$query mysql_query($sql);
    
    
// Little error checking and we are done
    
if(!$query){
        
        die(
mysql_error());
        
    }
            
}

// Now we have to get messages
// From database to see what other users are writing
function get_messages(){
    
    
// Now let's get all info from "chat" table
    
$sql "SELECT * FROM chat";
    
$query mysql_query($sql);
    
    
// Some error checking
    
if(!$query){
        
        echo 
"Can not get messages from database.";
        
    }else{
        
        
// If everything is fine let's display our messages
        // First to come is time, it will look like this (12:34)
        // Second is user's name and after that comes the text
        // For example: (13:54) Jaan: Hey there!
        
while($row mysql_fetch_array($query)){
            
            echo 
"(".$row[time].") "."".$row['user'].": ".$row['text']."
"
;
            
        }
        
    }    

}

// Now let's get users that are using this
// Chatroom, so people can see who they are talking
function get_users(){
    
    
// Let's get all info from "auth" table
    
$sql "SELECT * FROM auth";
    
$query mysql_query($sql);
    
    
// Check that everything is fine
    
if(!$query){
        
        echo 
"Can not get users from database.";
        
    }else{
        
        
// If everything is fine, let's display all users
        
while($row mysql_fetch_array($query)){
            
            echo 
"".$row['user']."

";
            
        }
        
    }
    
}

// Here's the engine that puts everything to work
// All functions are triggered when they are wanted
// For example we want to log our user out
// We put this link to our page:Logout
// And as you see when "act" isn't empty and "act" is "logout"
// Let's trigger logout() function that logs our user out
// Everything works the same with other functions

$act addslashes(htmlentities(htmlspecialchars($_GET['act'])));

if(
$act != "" && $act == "logout"){
    
    
logout();
    
}elseif(
$act != "" && $act == "login"){
    
    
process_login();
    
}elseif(
$act != "" && $act == "post"){
    
    
post_message();
    
}elseif(
$act != "" && $act == "getmessages"){
    
    
get_messages();
    exit;

}elseif(
$act != "" && $act == "getusers"){
    
    
get_users();
    exit;

}

?>

Now when this is done.. let's create our jQuery page that will make everything dynamical and you don't have to refresh page..(For next steps see part 2 of this article)
 

 
 

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: