I am having difficulty updating a range of columns using mysql. My overall goal is to give the user the ability to change a list item’s position and to have all of the other list items shift position to accommodate for the change. So say you have a range of numbers, 1-6 and you would like to move the item in position 2 to position 4 and have each item compensate for the change while each occupying only a single position number. I have been working on this for a few hours now and I am getting too tired to think straight. I am still very much a newbie with mysql but I have almost finished making my first cms except for this last annoying tidbit.
The code in question is:
$newposition = $_POST['position'];
$oldposition = $_GET['oldposition'];
$id = $_GET['id'];
while ($work = mysql_fetch_array($workset)) {
if ($newposition>$oldposition) {
mysql_query('UPDATE work SET position=position-1 WHERE position<='.$newposition.' AND position>'.$oldposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition<$oldposition) {
mysql_query('UPDATE work SET position=position+1 WHERE position<'.$oldposition.' AND position<='.$newposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition==$oldposition) {
echo 'same value! ';
}
}
It creates the requested position change correctly but all of the other numbers in the range get changed to an incorrect value. It is probably a simple mistake..
So, I came up with a solution for anyone that is interested. It isn’t the cleanest, but it appears to have worked..