Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

PHP MySQL multiple row updates with a single query

By: a guest on Apr 30th, 2011  |  syntax: PHP  |  size: 0.42 KB  |  views: 454  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. $cases  =   array();
  3. $referenceids = $_POST['ids']; // array(1, 2, 10, ...)
  4. $orderCounter = 0;
  5. foreach($referenceids as $rid)
  6. {
  7.         $orderCounter++;
  8.         $cases[]    =   'WHEN '.$rid.' THEN '.$orderCounter; // WHEN 1 THEN 1...
  9. }
  10. $query  =   'UPDATE `table` SET `column` = CASE `referenceid` '.implode("\n", $cases).' END WHERE `referenceid` IN('.  implode(',', $referenceids).')';
  11. $result =   mysql_query($query);
  12. ?>