SHARE
TWEET

PHP MySQL multiple row updates with a single query

a guest Apr 30th, 2011 505 Never
  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. ?>
RAW Paste Data
Top