In this article, Tim will show you how to create a quick-n-easy chat script using PHP and a very simple MySQL database. The script will allow visitors to choose a nickname, enter text to send to the chatting window, and view messages from other people... all in real-time! For a bit of fun, the chat application also has buttons to send several emote-icons including smiling and frowning faces.
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 function
The 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:
The output from the ShowLogin function looks like this:
The Login function
The 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:
<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.