if I have three menus
id | name | order
--------------------
1 | Foo | 1
2 | Bar | 2
3 | Blah | 3
and click the link menu/up/1, I need to set order of menu with id 1 to 2 and menu with id 2 to 1.
I have tried (PDO)
public static function goDown($id) {
if(!$id) {
return false;
}
self::connect();
self::prepare('SELECT count(*) FROM menu');
$count = self::fetch();
if(isset($count['count(*)'])) {
self::prepare('UPDATE menu SET order = order - 1 WHERE order = :count');
self::bindValue('count', $count['count(*)']);
self::execute();
self::prepare('UPDATE menu SET order = order + 1 WHERE id = :id AND order < :count');
self::bindValue('id', $id);
self::bindValue('count', $count['count(*)']);
return self::execute();
}
}
Thanks!
EDIT – MY SOLUTION:
public static function goDown($id) {
if(!$id) {
return false;
}
self::connect();
self::prepare('SELECT count(*) FROM menu');
$count = self::fetch();
if(isset($count['count(*)'])) {
self::prepare('SELECT ordem FROM menu WHERE id = :id LIMIT 1');
self::bindValue('id', $id);
$ordem = self::fetch();
self::prepare('UPDATE menu SET ordem = ordem - 1 WHERE ordem = :ordem');
self::bindValue('ordem', $ordem['ordem'] + 1);
self::execute();
self::prepare('UPDATE menu SET ordem = ordem + 1 WHERE id = :id AND ordem < :count');
self::bindValue('id', $id);
self::bindValue('count', $count['count(*)']);
return self::execute();
}
}
I don’t know how your table definition and keys are set up, but you will probably have to have an overlapping number for a split second. If that is ok, then do something like this:
The safest:
This uses an extra query, but is much safer. You can also validate that it isn’t at the top/bottom, too as that will cause problems.