Ordering Position Rows on mySQL table... Is this correct??

Discussion in 'PHP' started by fdoze, Nov 10, 2008.

  1. #1
    Hi,

    I'm trying to set a button to control a postition up and down on some rows that i got from mysql Table. I have a postition field.

    I'm using this code to go UP:
    		$myContentId = $_REQUEST['myId'];
    		$myContentPosition = $_REQUEST['myPos'];
    		
    		
    		$mySql1 = "UPDATE `highlights` SET `position` = $myContentPosition WHERE position = $myContentPosition-1 AND id != '".$myContentId."'";
    			$result1 = mysql_query($mySql1);	
    		
    		$mySql2 = "UPDATE `highlights` SET `position` = position -1 WHERE id = '".$myContentId."'";
    			$result2 = mysql_query($mySql2);	
    
    PHP:
    Is this correct???

    What is your method?


    Thanks in advance.
     
    fdoze, Nov 10, 2008 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    This is the way.

    For example you have 5 items.

    item 1
    item 2
    item 3
    item 4
    item 5

    and you want to move item 5 to the position of item 4, you have to do two things.

    1. Move item 4 to item 5 (pos++)
    2. Move item 5 to item 4 (pos--)

    that can be done with 2 queries
    1. fetch 2 rows (starting with the one that moves up/down)
    1. update 2 rows

    Hope this helped.
     
    EricBruggema, Nov 10, 2008 IP
  3. fdoze

    fdoze Peon

    Messages:
    205
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Could you please post an example?

    Mine code is working. But i was wondering if there is any better method of doing it.

    Becaus I'm assuming that the Position is sequencial...

    Thanks.
     
    fdoze, Nov 11, 2008 IP