Log in

View Full Version : Chat Script Error



Titan85
04-06-2007, 03:58 PM
I created a little script for live chat, but get an error whenever there are more than 10 entries. Here is my code:
<?php

function printMessage() {
$show = mysql_query("SELECT * FROM `chat` ORDER BY time") or die ('Error Getting Messages! <br />' .mysql_error());
while ($msg = mysql_fetch_array($show)) {
echo ''.date('h:m', $msg['time']).' '.$msg['user'].' >'.$msg['message'].' <br />
';
}
}


function addMessage($user, $message) {
$user = mysql_escape_string(strip_tags($_POST['user']));
$message = mysql_escape_string(strip_tags($_POST['message'], '<a><b><i><u>'));
mysql_query("INSERT INTO `chat` (id, time, user, message) VALUES ('10', 'time()', '$user', '$message')") or die ('Error Posting! <br />' .mysql_error());
mysql_query("UPDATE `chat` SET id = id-1") or die (mysql_error());
mysql_query("DELETE FROM `chat` WHERE id < 1") or die (mysql_error());
}


if ($_POST['send']) {
addMessage($user, $_POST['message']);
printMessage();
}


echo '
<!-- Chat Form -->
<form method="post" action="" name="chat">';
if (!$_COOKIE['chat']) {
if (!$_POST['send']) {
echo '
Username: <input type="text" name="user" />
<br />';
} else {
@setcookie('chat', strip_tags($user), time() + 3600);
echo '
<input type="hidden" name="user" value="'.$_POST['user'].'" />';
}
}
?>
Message: <input name="message" type="text" size="50" />
<input type="submit" name="send" value="Send" />
</form>
<!-- /Chat Form -->After it gets up to about 10 messages, it gives the error "Duplicate entry '9' for key 1". I know that it is something wrong with the addMessage function in the first and second sql queries, but can't figure out another way to do it. Here is my sql table in case you need it:
CREATE TABLE `chat` (
`id` int(4) NOT NULL auto_increment,
`time` varchar(10) NOT NULL,
`user` varchar(32) NOT NULL,
`message` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=HEAP AUTO_INCREMENT=1;I want it to only keep the latest 10 messages in the database. Any ideas? Thanks

Titan85
04-08-2007, 03:40 AM
Anybody have an idea of what I need to change?

Twey
04-08-2007, 01:17 PM
I'm guessing that you've got a non-unique ID in there somewhere, which isn't allowed since it's a primary key. Rather than using a VARCHAR(10) for the time field, you might want to use a DATETIME and the MySQL NOW() function.