开发者

mysql use CASE to update multiple rows with a for loop

I need to update 360 rows. obviously this doesn't work properly. Any help, please

for ($i = 1; $i <= 360; $i++)开发者_JAVA技巧 {

  $info  = mysql_real_escape_string($_POST[$i]);
  $check = mysql_real_escape_string($_POST[''.$i.'Check']);

      $case = "WHEN '$i' THEN '$info'";
}

  $sql = "UPDATE $table
            SET info = CASE id
              $case
            END
           WHERE ID in (1-360)";

  mysql_query($sql)
      or die (mysql_error());


There's at least one (not very?) obvious reason why this doesn't work - you're replacing the contents of $case with every iteration of the loop. $case .= "WHEN '$i' THEN '$info'\n"; (note the dot before the equal sign) might already get you further. Another one is probably that $i is put in single quotes inside the query while ID columns tend to be numeric.

I didn't try and run your code. If it still "doesn't work", you should edit your question and add more info like table structure and error messages.

Apart from that, you could do:

$sql = "UPDATE $table  SET\n";
for ($i = 1; $i <= 360; $i++) {

  $info  = mysql_real_escape_string($_POST[$i]);
  //$check = mysql_real_escape_string($_POST[''.$i.'Check']);
  // What's that $check for?

  $sql .= "info = '$info' where ID = $i\n";
}

mysql_query($sql)
  or die (mysql_error());

Running a batch of statements against the server is not uncommon and might even yield better performance than looking up the matching value in a 360 line CASE construct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜