A MySQL Driven Chat Script - The chat script explained
(Page 3 of 6 )
Our chat script will be created as only one file, named “chat.php”. It will contain four functions named ShowLoginForm, Login, GetInput and ShowAddPosts. These four functions are described below.
The ShowLoginForm functionThe ShowLoginForm function is called whenever a visitor loads our chat.php script for the first time. It will display a HTML form that contains a field for the user to enter their nickname into. Once this form is submitted, the Login function is called.
The code for the ShowLogin function looks like this:
function ShowLoginForm() {
?>
<b>Enter Your NickName</b>
<form name="chat" method="post" action="chat.php" target="_top">
<input type="text" name="nick" size="20">
<input type="hidden" name="action" value="enter">
<input type="hidden" name="chat" value="<font color=FF0000><b>Enters the Room</b></font>">
<input type="submit" name="Submit" value="Submit">
</form>
<?php
} The output from the ShowLogin function looks like this:
The Login functionThe login function is responsible for taking the users nickname (which is passed to the function from the login form created by the ShowLoginForm function) and creating a new session variable from it. This session variable will allow our chat script to track the user throughout their entire chat session, until they close their browser window. The login function also displays the actual frames for the chat page, by using one <frameset> HTML tag and two <FRAME> tags. The code for the Login function is shown below:
function Login() {
global $chat;
global $nick;
session_start();
session_register("nick", $nick);
?>
<frameset rows="563,62" cols="*">
<frame name="posts" src="chat.php?action=posts&nick=<?php echo $nick; ?>&chat=<?php echo $chat; ?>">
<frame name="form" src="chat.php?action=form&nick=<?php echo $nick; ?>">
</frameset>
<noframes>
<body>
<p>This page uses frames, but your browser doesn't support them.</p>
</body>
</noframes>
</frameset>
<?php
}The <frameset> tag creates two horizontal frames: The first (the main chat window, which will display the messages) is 563 pixels high. The second (which will allow the visitor to enter their message) is 62 pixels high. Pay careful attention to the “src” attribute of the two <frame> tags. You will notice that they pass an “action” value, as well as the users nickname as part of the URL’s query string. We will talk more about this in just a minute.
The output from the Login function looks like this:

Remember how we added a test record to the “chatscript” table when we were creating it? If you take a look at the screen shot above, you can see that it appears in the contents of our main chat window. The actual contents of the top and bottom frames shown above are generated by the GetInput and ShowAddPosts functions. They are described below.
Next: The chat script explained (contd.) >>
More MySQL Articles
More By Tim Pabst