简体   繁体   English

如何在MySQL中更新多个记录?

[英]How to update multiple records in MySQL?

I am trying to pull records from a table and update one filed in them. 我正在尝试从表中提取记录并更新其中的一个记录。 I am able to pull the records and create the form, however the update part is not working. 我能够提取记录并创建表单,但是更新部分无法正常工作。

The code below is above my HTML section. 下面的代码在我的HTML部分上方。

<?php require_once('../Connections/connect.php'); ?>
<?php
session_start();
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they log in. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "sorry.php";
if (!((isset($HTTP_SESSION_VARS['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $HTTP_SESSION_VARS['MM_Username'], $HTTP_SESSION_VARS['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $HTTP_SERVER_VARS['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
$col_points = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
  $col_points = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_points = sprintf("SELECT cam_registered_tbl.team_id_num, cam_registered_tbl.wins, cam_registered_tbl.losses, cam_registered_tbl.points, cam_teams_tbl.team_name, cam_registered_tbl.registered_id_num FROM cam_registered_tbl, cam_teams_tbl WHERE cam_registered_tbl.tournament_id_num=%s AND cam_teams_tbl.team_id_num=cam_registered_tbl.team_id_num", $col_points);
$points = mysql_query($query_points, $camsports) or die(mysql_error());
$row_points = mysql_fetch_assoc($points);
$totalRows_points = mysql_num_rows($points);

$col_tournament = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
  $col_tournament = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_tournament = sprintf("SELECT cam_tournaments_tbl.tournament_name FROM cam_tournaments_tbl WHERE cam_tournaments_tbl.tournament_id_num=%s", $col_tournament);
$tournament = mysql_query($query_tournament, $camsports) or die(mysql_error());
$row_tournament = mysql_fetch_assoc($tournament);
$totalRows_tournament = mysql_num_rows($tournament);
?>
<?php

//This loops through all the records that have been displayed on the page.

for ($index = 0; $index <= $index_count; $index++) {


    /*
    This part sets a variable with the names we created in the first section.  
    We start with 0 and go until the number saved in the $index_count variable.
    */ 

    $varregistered_id_num = 'registered_id_num'.$index;
    $varteam_name = 'team_name'.$index;
    $varwins = 'wins'.$index;
    $varlosses = 'losses'.$index;
    $varpoints = 'points'.$index;


    /*
    This is the variable variable section.  We take the value that was assigned 
    to each name variable.  For example the first time through the loop we are 
    at the record assigned with SubmissionID0.  The value given to SubmissionID0 
    is set from the first section.  We access this value by taking the variable 
    variable of what SubmissionID0 is.
    */

    $registered_id_numvalue = $$varregistered_id_num;
    $team_namevalue = $$varteam_name;
    $winsvalue = $$varwins;
    $lossesvalue = $$varlosses;
    $pointsvalue = $$varpoints;


    //Update the database

    $sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',".
        "losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
    $result = mysql_query($sql);

    //If the link was marked approved set the value of the Approved field

    if ($goto == '1') {
        $insertGoTo = "menu.php";
        header(sprintf("Location: %s", $insertGoTo));
    }


}

?>

This code is in the body section 该代码在正文部分

<div align="center">
  <p><font size="4"><?php echo $row_tournament['tournament_name']; ?></font></p>
  </div>
<?php
//Initialize counter variables

$index = 0;
$index_count = 0;
echo "<form method=post action=$PHP_SELF>\n";
echo "<table>\n";
echo "<tr><td><b>Team</b></td>".
    "<td><b>Points</b></td></tr>\n";


/*
Assuming we already have retrieved the records from the database into an array setting 
$myrow = mysql_fetch_array().  The do...while loop assigns a value to the $xstr variable 
by taking the name and concatenating the value of $index to the end starting with 0.  So 
the first time through the loop $SubmissionIDStr would have a value of SubmissionID0 the 
next time through it would be SubmissionID1 and so forth.
*/

do {

$registered_id_numStr = registered_id_num.$index;
$team_nameStr = team_name.$index;
    $pointsStr = points.$index;


//This section would print the values onto the screen one record per row

printf("<tr><td><input type=hidden name=%s value=%s>%s</td>
<td><input type=text name=%s value=%s size='5'></td></tr>\n", 
$registered_id_numStr, $row_points["registered_id_num"], $row_points["team_name"], $pointsStr, $row_points["points"]);


//Increase counter values by 1 for each loop

$index++;
$index_count++;

} while ($row_points = mysql_fetch_array($points));

// I also had to create an index count to keep track of the total number of rows.

echo "<INPUT TYPE=hidden NAME=counter VALUE=$index_count>\n";
echo "<INPUT TYPE=hidden NAME=goto VALUE='1'>\n";

echo "<INPUT TYPE=submit></form>\n";
 echo "</table>";

?>

Any help would be greatly appreciated. 任何帮助将不胜感激。

You are doing it right - I don't know of any better approach for your case than running update in for loop. 您做对了-我不知道有比在for循环中运行update更好的方法。 What you should do is to enclose this in a transaction: 应该做的就是将此包含在事务中:

mysql_query("start transaction");
for ($index = 0; $index <= $index_count; $index++) {
     ...
     $sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',"."losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
     $result = mysql_query($sql);
     if (!$result) { // you possibly should do some error checking
          mysql_query("rollback"); // cancel the transaction
          //print error
          exit(0); 
     }
     ...
}
mysql_query("commit"); // commit the transaction

If you don't use the transaction, you might end up with just some of the records updated, which will leave the database in inconsistent state. 如果不使用事务,则最终可能只会更新一些记录,这将使数据库处于不一致状态。 Transaction is very important here - with it, all of the records are updated, or none. 事务在这里非常重要-使用它,所有记录都将更新,或者不更新。

Make sure you use the InnoDB engine, in MyISAM engine the transactions do not work. 确保使用InnoDB引擎,在MyISAM引擎中,事务不起作用。

I didn't read the whole code, but if you have multiple records and you wish to update the same field (with the same value), you can achieve it like this: 我没有阅读完整的代码,但是如果您有多个记录,并且希望更新相同的字段(具有相同的值),则可以这样实现:

UPDATE mytable SET filed = '$value' WHERE id IN (1,2,3,4,5)

if you have an array with ids, you can do it like this: 如果您有一个包含ID的数组,则可以这样操作:

$ids = implode(',',$array_ids);
UPDATE mytable SET field = '$value' WHERE id IN ('$ids')

BUT If the values are different for each id, just run a loop that updates values for each row. 但是,如果每个id的值不同,则只需运行一个循环以更新每一行的值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM