How can you ensure a dynamic numbering system in PHP when the ID field is not sorted due to deletions?

When records are deleted from a database table with an auto-increment ID field, the numbering system can become non-sequential. To ensure a dynamic numbering system in PHP, you can use a query to re-order the IDs based on their current order in the table. This can be achieved by fetching all records, updating the ID field with a new sequential number, and then saving the changes back to the database.

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Fetch all records from the table
$query = "SELECT * FROM table_name";
$result = $connection->query($query);

// Initialize a counter variable
$counter = 1;

// Update the ID field with a new sequential number
while ($row = $result->fetch_assoc()) {
    $updateQuery = "UPDATE table_name SET id = $counter WHERE id = " . $row['id'];
    $connection->query($updateQuery);
    $counter++;
}

// Close the database connection
$connection->close();