Registering will remove adverts, allow you to talk with other webmasters on our forums and give you access to 'members only' extras! Click here to register...

Latest Script Release: Stash News V1.1.1     Latest Template Release: Luv
Login:
WebmasterStash.com
Photoshop: What is High Dynamic Range and How Do Y Photoshop: What is High Dynamic Range and How Do Y...
What is dynamic range? According to that great source of public information, Wikipedia, i...
Make A Simple Shoutbox / Chatroom Part 1 Make A Simple Shoutbox / Chatroom Part 1...
This tutorial explains how to use PHP to make a shoutbox or chat room for your site. Part ...
Creating Photoshop Website Templates Creating Photoshop Website Templates...
Creating Photoshop website templates tutorials is a good start for beginners who have a li...
Creating a Website Design Templating System Using Creating a Website Design Templating System Using ...
Learn how to create a website design templating system using php to be able to easily upda...
The Benefits of Search Engine Optimization The Benefits of Search Engine Optimization...
We have all heard of the importance of SEO when it comes to getting your website known in ...
Join The WebmasterStash Community Today! - It's FREE!
(If you were logged in you wouldn't be seeing these adverts. Login or Register Now!)

Make A Simple Shoutbox / Chatroom Part 1

Submitted By Staff On 28th Mar 2008 - 6:20pm :: Report Tutorial :: Go Back to Tutorial Listings


Ever wanted to have a shoutbox on the side of your site? Or maybe a chat room? Great! In this tutorial I'm going to show you how to do just that. At the end, you'll have a front end which will have a form to add a message, and a window to show the latest entry's. You'll also have an admin area to remove bad posts, however this will be covered in part two, which will be added soon! Ok, so our first step. Create a folder to do this project in, you'll need access to a web server with PHP and MySQL. If you dont have one, you can download free ready-to-go servers for your own computer. Google the term WAMP (Windows users), LAMP (Linux users) or MAMP (Mac OS X users). Once you've got your server, and your folders created your ready to go. Create a new file in the folder. Ours is called simply 'index.php'. Open it up with your favorite code editor (I.E Notepad, Dreamweaver, etc) and place a basic HTML layout in it like this:
<html>
<head>
<title>WebmasterStash Simple Shoutbox</title>
</head>
<body>



</body>
</html>
This will form the page for our script, you can of course edit this and add extra content and styles, however for this tutorial, we're keeping it simple ;) Next, we need to setup our database connection. However first, we need a database so open PHPMyAdmin and make a new database....call it what you like, ours was called 'shoutbox_tutorial'. Once its created, we need a table thats going to store all those posts in the shoutbox. We're calling this simply 'shoutbox' and it will have 5 fields. These are:
  • id
  • username
  • comment
  • dateline
  • ipaddr
I think its pretty self explanatory what each of the fields are. Heres how our structure looks:
CREATE TABLE `shoutbox` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 50 ) NOT NULL ,
`comment` TEXT NOT NULL ,
`dateline` TIMESTAMP NOT NULL ,
`ipaddr` VARCHAR( 15 ) NOT NULL
) ENGINE = MYISAM ;
Ok, now onto the connection. The script uses a standard PHP function to connect to our database, this allows the data to be sent/received via forms and such in the script.
<?php 

$conn 
mysql_connect("localhost""root""");
$db mysql_select_db("shoutbox_tutorial"$conn);

?>
The above shows how your connection should look, the 'mysql_connect' function has three options. The first is the host (which is usually 'localhost' unless you use a provider that uses separate sql servers), the second is the username and the third, the password. The mysql_select_db line contains the database name. You need to make sure your user has the appropriate permissions on the database you are connecting to, otherwise you'll have problems! Next, we're going to create an if statement, this will contain the list of posts, which will be refreshed ever 6 seconds to get the latest data from the database. It will basically connect, check for new posts, and output them. To prevent there being too many overheads, I've limited the query to allow only the last 25 posts to show. I would advise no more than this, as thats 25 queries, every 6 seconds from each user! Heres how ours looks at this point with the if statement and the query:
<?php 

$conn 
mysql_connect("localhost""root""");
$db mysql_select_db("shoutbox_tutorial"$conn);

if(
$_GET['postview'] == "true") {
    
    
$sql=mysql_query("SELECT * FROM shoutbox ORDER BY id DESC LIMIT 25");
    
    
}else {
    
    
// We've not done this bit yet!
    
}

?>
Ok, that query's not doing much at the moment. We're now going to fetch the details from each post using a "while" statement. This is a loop that will pick up all 25 of the latest posts and dump them to the screen.
<?php 

while($r=mysql_fetch_array($sql)) {
        
        
        
    }

?>
Inside the above code, we'll use the "$r" variable to gain the information from the database, format it, and then show it! I decided to format it like so:
[01st Jan 13:00] Username: The comment goes here
Quite simple, and easy to read :) This is how our loop now looks:
<?php 

    
while($r=mysql_fetch_array($sql)) {
        
        
// Lets fetch the details from the database shall we!
        
$username     stripslashes($r['username']);
        
$dateline     stripslashes(date("jS M G:i"$r['dateline']));
        
$comment    stripslashes(strip_tags($r['comment']));
        
// We dont need the IP or ID for this part, so lets not bother fetching useless information.
        
        
echo'['.$dateline.'] <strong>'.$username.':</strong><br />
             '
.$comment.'
             <hr style="border-bottom: 1px dotted #555555;" align="center" size="0" color="#FFFFFF" />'
;
        
    }

?>
And this has produced the following:
PHP & MySQL Shoutbox Tutorial
Now, we want this age to refresh every 6 seconds, so it gets the latest shouts/posts. To do this we use a META refresh tag. As long as its 'echoed' and is within the if statement, it will work...just don't put it within the while statement. For this tutorial, I put it just before the closing tags of the if statement, right before the "}else {". Heres the code:
<?php 
echo'<meta http-equiv="refresh" content="5"/>';
?>
Great! We're done with the fetching part. Now we need to do the 'else' statement, which will contain the form to add a comment, as well as a frame to show the latest shouts. We're going to start off by creating another if statement that will process the form:
<?php 

    
if($_POST['submit']) {
        
        
$username     strip_tags(addslashes(htmlentities($_POST['username'])));
        
$comment     strip_tags(addslashes(htmlentities($_POST['comment'])));
        
$ipaddr        $_SERVER['REMOTE_ADDR'];
    
        
$sql=mysql_query("INSERT INTO shoutbox (username, comment, ipaddr) 
        VALUES('$username', '$comment', '$ipaddr')"
);
        
        if(
$sql) {
            echo
'<strong>Comment Added Successfully!</strong>';
        }
        
    }

?>
Now, we're going to make the form, it needs to include the username and comment fields like so:
<?php 

echo'<form action="" method="POST">
            <fieldset>
            <b>Username:</b> <input type="text" name="username" maxlength="50" size="10" />
            <b>Comment:</b> <input type="text" name="comment" maxlength="500" size="30" />
            <input type="submit" name="submit" value="Post »" />
            </fieldset>
        </form>'
;

?>
Now our form is done, and working, we're going to add the iframe to the page, this shows all the results, and is reloaded every 6 seconds. I wanted it above the form so I placed the code just before the form's if statement. I also used a table to enclose all the content.
<?php 
    
echo'<table width="600" align="center">
            <tr>
                <td align="center">
                <iframe src="?postview=true" width="600" height="250" align="center"></iframe>
                </td>
            </tr>
            <tr>
                <td>'
;

?>
I closed the table below the form like so:
<?php 
echo'</td>
        </tr>
      </table>'
;
?>
And we're done! Well, the front-end at least. I've placed a copy of the entire code on the next page, just in case you missed anything! I'll be posting part two at a later date, which will show you how to create an admin area to manage your shoutbox or chatroom!
Shoutbox Chatroom Tutorial


« 1 2 »
Back to Top :: Go Back to Tutorial Listings


Copyright © 2008 WebmasterStash All Rights Reserved.
A Rike Media Production

Advertising Opportunities     Privacy Policy / Disclaimer     Contact Us     Community Forums