1

I have an sql table with articles in it. I stored the order of the articles in an INT field in sql.
With an ajax post from the (drag and drop) UI, i got an array with integers (new order).
example:
Old order: 2,1,3,4
New order should be: 2,1,4,3
php:

$i = 1;    
foreach ($inputarray as $var) :
        if ($i != $var) :
            $this->_sqli->query("UPDATE articles 
    SET artorder=$i WHERE artorder = $var and pagesid = $pagesid");
        endif;

    $i++;
endforeach;

The problem: when i try to swap elements, they are gonna be the same. So the previous example's output will be: 2,1,4,4 How should i update my sql?

2 Answers 2

1

This will not work as long as "artorder" is the unique key that you use when updating a row. This is because you will run into situations where the artorder is the same in two rows; thus, you no longer have a unique key. Just add a primary key to the table and use that on your UPDATE statements:

ALTER TABLE articles ADD articleId INT(5) NOT NULL,
ADD PRIMARY KEY (articleId) 
Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass the old order as well as the new order. Then you could write

$sz = count ($inputarray);
for ($i = 0; $i < $sz; ++$i):
    // $oldarray holds the old order
   if ($oldarray[$i] != $inputarray[$i]) :
      $this->_sqli->query("UPDATE articles 
         SET artorder=" . $inputarray[$i] . " WHERE artorder = " . $oldarray[$i] . " and pagesid = $pagesid");
      endif;
endfor;

2 Comments

I got the same result with this. :(
Yes, I just realised what the problem is. Using your example, on the 3rd iteration it changes artorder to 4 from 3 - so there are two rows wth artorder = 4. On the 4th iteration, it changes all artorder values of 4 to 3 :( Doh! Is there another way to uniquely refer to rows other than artorder? I think you will need this to avoid the problem of updating the same column that you are using to select on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.