Home > Backend Development > PHP Tutorial > php实现只保留mysql中最新1000条记录_php实例

php实现只保留mysql中最新1000条记录_php实例

WBOY
Release: 2016-06-07 17:12:38
Original
795 people have browsed it
<&#63;php 
mysql_connect("localhost","root","root");
mysql_select_db("test");
//保留最新的1000条记录
$limit=1000;
$query="select `id` from `news`";
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num>$limit){
$query="select `id` from `news` order by `id` desc limit ".$limit;
$result=mysql_query($query);
mysql_data_seek($result,$limit-1);
$data=mysql_fetch_array($result);
$query="delete from `news` where `id`<'$data[id]'";
if(mysql_query($query)){
echo "数据库中原有".$num."条记录,多余的".($num-$limit)."条记录被成功删除,现在还剩余".$limit."条记录!";
}
}else{
echo "数据记录不足".$limit."条!没有必要删除!";
}
&#63;>

Copy after login

test.sql

-- phpMyAdmin SQL Dump
-- version 3.1.5-rc1
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2010 年 08 月 19 日 05:47
-- 服务器版本: 5.0.18
-- PHP 版本: 5.2.8

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- 数据库: `test`
--

-- --------------------------------------------------------

--
-- 表的结构 `news`
--

CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
Copy after login

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template