Reorder table id [PHP & Mysqli]

Asked

Viewed 59 times

0

Hello, I’m in a project where the order of id’s is quite important for the final result, but when removed a row of table is left an empty id... Ex.:

inserir a descrição da imagem aqui

If I delete id 2 it will look like this...

inserir a descrição da imagem aqui

I wanted the code after I deleted it to change all the ID’s... I already removed the auto-increment to modify but n with you ta ai my code where $mate = table name_table;

<?php

include"default.php";

if (isset($_GET['mat']) && isset($_GET['id'])) {
    $mat = $_GET['mat'];
    $id = $_GET['id'];

    include"../ligacao.php";

    $query = mysqli_query($conexao, "SELECT * FROM ".$mate);
    $linhas = mysqli_num_rows($query);

    if ($linhas == $id) {
        mysqli_query($conexao, "DELETE FROM ".$mate." WHERE id = '$id'");
    } elseif ($id < $linhas) {
        mysqli_query($conexao, "DELETE FROM ".$mate." WHERE id = '$id'");
        $idn = 1;
        while ($idn > $linhas) {
            mysqli_query($conexao, "UPDATE ".$mate." SET id = '$idn'");
            $idn ++;
        }
    }

} ?>

The result is just deleting the line without changing the id’s of the others.

What I do ?

  • This is crazy... I would have to update each line by changing the primary key... the primary key exists to be unique and not be changed. Explain what would be "important to the end result" that there is certainly another way to do what you need

  • You can create another column in the table, for example, code, and change this value, but not the id. Or in the table do a i++ in the loop and print in the first column

1 answer

0


this makes no sense. ids are a unique identifier in the ecosystem and are not interchangeable and should not be. If Goytai has ID 1 and I have ID 2, if you die from natural causes you cannot give your id to another person as that ID is the number that identifies you to SI and SO to SI in life or death.

  • Thank you very much... If I created a new column in the table and used it as an "ID" without being the primary key, this code structure would work in the proposed new system ?

  • yes. creating another column can change the values as you like using UPDATE or when creating the new widget.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.