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

一.创建一个数据库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自动重新自增排序

上一篇:自定义的JDBC工具类(代码参考)


下一篇:java测试类向订单表插入数据,程序没有错误运行也正常,但是查看数据库时发现数据库未插入数据怎么办?