zoukankan      html  css  js  c++  java
  • 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');
    
     ?>
  • 相关阅读:
    localX mouseX stageX
    帮陈云庆做的手机报
    另一种换行排列方块的方法
    换行排列(思路源自陈勇源代码)
    网上摘的
    ASP.NET页面间数据传递(转)
    数据库连接字符串大全 之 SQL服务器篇
    保存一个免费的在线的图片转换工具网站,支持BMP,JPG,IOC,PNG和GIF
    关于IE6和IE7以及多个版本IE共存的问题
    如何测试sql语句性能,提高执行效率
  • 原文地址:https://www.cnblogs.com/wlei5206/p/12755478.html
Copyright © 2011-2022 走看看