PHP implements automatic re-incremental sorting of MySQL's primary key id

1. Create a database db_idlist to execute SQL code

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;

2. New index.php

<? php 

$ conn = mysqli_connect ("127.0.0.1", "root", "123456", "db_idlist") or die ("Database server connection error". mysqli_error ( $ conn ));
      mysqli_select_db ( $ conn , "db_idlist ") or die (" Database access error ". mysqli_error ( $ conn ));
      mysqli_query ( $ conn ," set names utf-8 " ); 

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

if (!$ query ) {
   exit ('<h1> Query data failed </ 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>

Three. Create listid.php

<? php 

$ conn = mysqli_connect ("127.0.0.1", "root", "123456", "db_idlist") or die ("Database server connection error". mysqli_error ( $ conn ));
      mysqli_select_db ( $ conn , "db_idlist ") or die (" Database access error ". mysqli_error ( $ conn ));
      mysqli_query ( $ conn ," set names utf-8 " ); 

$ sql =" alter table tb_idlist drop column id; "; // Delete the original The id field in the table 

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

    if (! $ query ) {
         exit ('<h1> Query data failed </ h1>' ); 
    } 

$ sqll = "alter table tb_idlist add id mediumint (8) not null primary key auto_increment first; "; // Reset the id primary key and automatically increment from 1 



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

    if (! $ Query ) {
         exit ('<h1> Failed to query data </ h1> ' ); 
    } 

header (' Location: index.php ' );

 ?>

 

Guess you like

Origin www.cnblogs.com/wlei5206/p/12755478.html