Ok, and now - as promised! The shoutbox I programmed! *Drum roll*
Kay. Now, I used two pages, one to display the messages and one to add a new message to the MySQL table.
Here's the easy part, printing out the table:
Code: Select all
$result = mysql_query("SELECT * FROM shoutbox ORDER BY `id` DESC") or die(mysql_error());
if ($result && mysql_num_rows($result)) {
$numrows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
print $row['name'].": ".$row['message'];
print "<BR />";
}
}
As you can see this is juat a raw read and output procedure; Nothing more than that.
Moving on, to the more sophisticated part. I decided that a round 15 is the optimal amount for messages to be stored and viewed for a shout-box. Of course you might think differently. Anyway, I see no point in keeping those messages who are beyond that 15-tops limit. Then what we (that is, I) need to do, actually, is delete the oldest message in the table every time a new message is added to the shout-box. This is done this way:
Code: Select all
mysql_query("DELETE FROM shoutbox WHERE `id` = 1") or die(mysql_error());
for($i=2; $i<=15; $i++)
{
$temp=$i-1;
mysql_query("UPDATE `shoutbox` SET `id` = \"{$temp}\" WHERE `id` =\"".$i."\" LIMIT 1;") or die(mysql_error());
}
mysql_query("INSERT INTO shoutbox (id, name, message) VALUES (15, \"".$_POST['name']."\", \"".$_POST['message']."\");") or die(mysql_error());
As you can see, the first query deletes the row with id=1, i.e. the oldest message.
Code: Select all
DELETE FROM shoutbox WHERE `id` = 1
Next thing I do, is decrease all the IDs of the 14 rows still in the table by 1. (for loop)
The final step is to add the new message - and give it the ID of 15! This way it gets to the back of the line.
Code: Select all
INSERT INTO shoutbox (id, name, message) VALUES (15, \"".$_POST['name']."\", \"".$_POST['message']."\");
As you can see this shout-box algorithm works according to the principle of FiFo - First in First out.