php中mysql定期删除,使用PHP和MYSQLi在数据库中每24小时删除数据

I like to know how you do this:

I have made a sort of a chatbox that automatic updates it self with a script and it loads up the latest 50 chat messages from database.

Now i wonder, how to delete messages after each 24 hours but keep the first new 50 messages and delete the older ones after that.

Is this possible with MYSQLi and PHP or must i do it with a better solution?

UPDATE

Followed advise from Lund and a fast response from my provider:

I am not able to do Cron Jobs or MYSQL Events with my current plan.

Also i do not have the money for upgrading it, so erm.... if there is

another solution, thank you for helping me out on this matter folks.

I have a table called: chatbox

and have this in it:

C_ID

chattext

name

date

解决方案

Pseudo code (Won't actually work without some edits to fit your code, but its an idea) - I don't know how your data is stored, or its variable names. Or your table name. Or basically any information that I would need to actually get this to work.

$sql = ("SELECT * FROM ChatLog ORDER BY TimeAdded DESC"); //Order by descending should show the newest ones first.

$index = 1; //set an index to loop through

while($row = mysqli_query($con, $sql) { //use a while loop to go through the table

if($index <= 50) { //for the first 50 records

//do nothing

} else { //for everything after 50 records

$chatId = $row['chatLogID']; //ID or unique value for the actual message.

$sql = ("DELETE FROM ChatLog WHERE chatLogID='$chatId'"); //Delete it from the table

mysqli_query($con, $sql);//Execute query.

}

}

You can set this up to execute everytime a message is stored, or check it against the current time of the server to remove it daily.

UPDATE: THIS CODE SHOULD BE WORKING WITH YOUR CODE

$sql = ("SELECT * FROM chatbox ORDER BY time DESC"); //Order by descending should show the newest ones first.

$index = 1; //set an index to loop through

while($row = mysqli_query($con, $sql) { //use a while loop to go through the table

if($index <= 50) { //for the first 50 records

//do nothing

} else { //for everything after 50 records

$chatId = $row['C_ID']; //ID or unique value for the actual message.

$sql = ("DELETE FROM chatbox WHERE C_ID='$chatId'"); //Delete it from the table

mysqli_query($con, $sql);//Execute query.

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值