首页 > 数据库技术 > 详细

PHP实现MySQL的主键id自动重新自增排序

时间:2020-04-22 20:06:43      阅读:212      评论:0      收藏:0      [点我收藏+]

一.创建一个数据库db_idlist执行SQL代码

DROP TABLE IF EXISTS `tb_idlist`;
CREATE TABLE `tb_idlist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

二.新建index.php

<?php 

$conn=mysqli_connect("127.0.0.1","root","123456","db_idlist") or die("数据库服务器连接错误".mysqli_error($conn));
     mysqli_select_db($conn,"db_idlist") or die("数据库访问错误".mysqli_error($conn));
     mysqli_query($conn,"set names utf-8");

$query = mysqli_query($conn, ‘select * from tb_idlist;‘);

if (!$query) {
  exit(‘<h1>查询数据失败</h1>‘);
}

while ($item = mysqli_fetch_assoc($query));

?>

<!DOCTYPE html>
<html>
<head>
    <title>ID重新排序</title>
</head>
<body>
    <table align="center">
        <h1><a href="listid.php">排序</a></h1>
        <tr>
        <th scope="row"><?php echo $item[‘id‘]; ?></th>
         <td><?php echo $item[‘content‘]; ?></td></tr>
    </table>
</body>
</html>

三.创建listid.php

<?php 

$conn=mysqli_connect("127.0.0.1","root","123456","db_idlist") or die("数据库服务器连接错误".mysqli_error($conn));
     mysqli_select_db($conn,"db_idlist") or die("数据库访问错误".mysqli_error($conn));
     mysqli_query($conn,"set names utf-8");

$sql = "alter table tb_idlist drop column id;";//删除原有表中的id字段

$query = mysqli_query($conn,$sql);
    echo mysqli_error($conn); 

    if(!$query){
        exit(‘<h1>查询数据失败</h1>‘);
    }

$sqll = "alter table tb_idlist add id mediumint(8) not null primary key auto_increment first;";//重新设置id主键并自动从1开始自增



$query = mysqli_query($conn,$sqll);
    echo mysqli_error($conn); 

    if(!$query){
        exit(‘<h1>查询数据失败</h1>‘);
    }

header(‘Location: index.php‘);

 ?>

 

PHP实现MySQL的主键id自动重新自增排序

原文:https://www.cnblogs.com/wlei5206/p/12755478.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!