How can the use of auto-increment fields in a database impact the sorting and swapping of menu items in PHP?

When using auto-increment fields in a database to store menu items, the sorting and swapping of menu items can be challenging as the auto-increment values are typically used as the primary key. To address this issue, you can create a separate column in the database table to store the order of the menu items. This column can be manually updated to reflect the desired order of the menu items, allowing for easy sorting and swapping in PHP.

// Assuming a database table named 'menu_items' with columns 'id', 'name', and 'order'
// 'id' is the auto-increment field and 'order' is the column for storing the order of the menu items

// Retrieve menu items in the desired order
$query = "SELECT * FROM menu_items ORDER BY `order` ASC";
$result = mysqli_query($connection, $query);

// Display menu items
while($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}

// Swap two menu items
$query = "UPDATE menu_items SET `order` = CASE
            WHEN `name` = 'Item 1' THEN 2
            WHEN `name` = 'Item 2' THEN 1
            ELSE `order`
          END";
mysqli_query($connection, $query);