I have a members table in MySQL
CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB;
And I would like to let users order the members how they like. I’m storing the order in order column.
I’m wondering how to insert new user to be added to the bottom of the list. This is what I have today:
$db->query('insert into members VALUES (0, 'new member', 0)'); $lastId = $db->lastInsertId(); $maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members'); $db->query('update members SET `order` = ? WHERE id = ?', array( $maxOrder[0]['max_order'] + 1, $lastId ));
But that’s not really precise while when there are several users adding new members at the same time, it might happen the MAX(order) will return the same values.
How do you handle such cases?
You can do the SELECT as part of the INSERT, such as:
Keep in mind that you are going to want to have an index on the
ordercolumn to make the SELECT part optimized.In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever.
Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well.