Mini-Chat Tutorial - Improving
(Page 3 of 4 )
Since only a small number of messages are to be printed out, why keep other messages in our DB? We can, of course keep them for logging, but I prefer dropping them. So we update our DB by adding a field to order messages and we update our 'addMessage' function to ensure that no more than the desired number of messages is kept.
<?php /* CREATE TABLE MINICHAT ( NB tinyint(4) NOT NULL auto_increment, LOGIN varchar(20) NOT NULL default '', MESSAGE varchar(255) NOT NULL default '', ITSTIME varchar(10) NOT NULL default '', PRIMARY KEY (NB), UNIQUE KEY NB (NB), KEY NB_2 (NB) ); */
// Add message into minichat function addMessage( $login, $message ) {
$login = mysql_escape_string( strip_tags( $login ) ); $message = mysql_escape_string( strip_tags( $message, '<a><b><i><u>') ); mysql_query( "INSERT INTO MINICHAT ( NB, ITSTIME, LOGIN, MESSAGE ) VALUES ( '10', '". time()."', '".$login."','".$message."' )" ); mysql_query( "UPDATE MINICHAT SET NB=NB-1" ); mysql_query( "DELETE FROM MINICHAT WHERE NB < 1" ); } ?> |
Since we have the time of each post, we can keep it and improve our print function. The second thing to do is to remove the LIMIT in the query, since now no more than 10 messages stay in the DB:
<?php // Prints messages function printMessages() { $rs = mysql_query( "SELECT * FROM MINICHAT ORDER BY ITSTIME" );
while ( $msg = mysql_fetch_array( $rs )) { echo date( 'h:m', $msg['ITSTIME'] )." ".$msg['LOGIN']." >".$msg['MESSAGE']."<br>"; } } ?> |
Now we'll drop that login box that appears each time the form is shown. For this, we'll update our print function to have it test if the box has to appear. A cookie will be set to keep your login if possible. If not, the login will stay in an hidden field.
<html> <head> <title>Mini Chat Sample</title> </head> <body> <form method="post"><br> <?php if ( !$_COOKIE['minichatlogin'] ) { if ( !$_POST['login'] ) echo 'Login:<input type="text" name="login" size="6"><br>'; else { @setcookie( "minichatlogin", strip_tags( $login ) ); echo '<input type="hidden" name="login" value="'.$_POST['login'].'">'; } } ?> Message:<input type="text" name="message" size="10"><br> <input type="submit" value="Send"><br> </form> </body> </html> |
Like this, the setcookie call will always fail since some html as been printed before the call, so we put all this in a func and reorganize the code to arrive to our final script.
Next: Final Script >>
More Miscellaneous Articles
More By Codewalkers