Click to See Complete Forum and Search --> : how limit amount of possible records to shoutbox database?


Annaccond
03-26-2007, 07:51 PM
I made simple shoutbox on my site and I have some question:

can I limit amount of possible records to table and make to after reach of some count of added records (for ex. 100 messages) old records be automatically deleted (and replaced by new records)?

I know how limit amount of messages showing on site but can I do anything to database stop grow (without necessity go to database and delete records manually)? :rolleyes:

NogDog
03-26-2007, 08:00 PM
Normally, I'd say, "don't worry about it." Unless you're expecting to get many tens of thousands of entries, it really should not impact your database performance (assuming a reasonably designed DB schema with proper indexing).

Anyway, if you think it's necessary, if you're using an auto-increment key field, you could do something like the following (assuming MySQL as the DBMS):

$result = mysql_query($insertQuery);
if($result)
{
$lastId = mysql_insert_id();
}
$sql = "DELETE FROM table_name WHERE id_nbr < $lastId - 100";
$result = mysql_query($sql);

Annaccond
03-26-2007, 09:42 PM
If it would work than I think it could solve also my previous problem but first I want to check is this work at all. Could you tell me please where exactly put part of code which you wrote in code of my actual shoutbox? I worry that something can demand change and I'll screw it again. And do I need replace id_nbr by some value or leave it as it is?

This is part of my actual shoutbox code (the rest it's just form):
<?
mysql_connect("localhost","username","password");
mysql_select_db("shoutbox");

if($submit)
{
$time=date("h:ia d/j/y");

$result=MYSQL_QUERY("INSERT INTO shoutbox (id,name,message,time)".
"VALUES ('NULL','$name', '$message','$time')");
}

$result = mysql_query("select * from shoutbox order by id desc limit 10");

while($r=mysql_fetch_array($result))
{
$time=$r["time"];
$id=$r["id"];
$message=$r["message"];
$name=$r["name"];
?>
<? echo $time ?><br>
<? echo $name ?><br>
<? echo $message ?><br>
<? }

?>

NogDog
03-26-2007, 10:51 PM
Assuming id is an auto-increment field (which it appears to be):

if($submit)
{
$time=date("h:ia d/j/y");

$result=MYSQL_QUERY("INSERT INTO shoutbox (id,name,message,time)".
"VALUES ('NULL','$name', '$message','$time')");
if($result != FALSE and mysql_affected_rows())
{
$lastId = mysql_insert_id();
$sql = "DELETE FROM shoutbox WHERE id < $lastId - 100";
$cleanup = mysql_query($sql);
if($cleanup == FALSE)
{
user_error("Cleanup query failed ($sql): " . mysql_error());
}
}
}

Annaccond
03-27-2007, 10:22 AM
Yes id is auto-increment. Now working perfectly. Thank you very much for help NotDog :)