如何使用计算在一个查询中更新数据库中的多个行

时间:2016-01-31 14:18:58

标签: php mysql rows

当我点击提交时,我应该如何更改代码以便一次更新多行?

这是代码:

<html>
<title></title>
<head>
</head>
<body>
    <form action="" method="post">
     <table>
      <tr>
       <td><h6>Seatwork 1</h6></td>
       <td><h6>Seatwork 2</h6></td>
       <td><h6>Seatwork 3</h6></td>
       <td><h6>Quiz 1</h6></td>
       <td><h6>Quiz 2</h6></td>
     </tr>

     <?php




        $query1="SELECT * FROM tbl...";
        $query = mysql_query($query1) or die(mysql_error());
          while($user = mysql_fetch_assoc($query)){

              $userid = $user['userid'];
              $first = $user['first_name'];
              $last = $user['last_name'];
              $subject = $user['subject'];                                
              $sw1 = $user['sw1'];
              $sw2 = $user['sw2'];
              $sw3 = $user['sw3'];
              $qz1 = $user['qz1'];
              $qz2= $user['qz2'];



            ?>  
        <tr>
          <td><h6><?php echo $first; ?>&nbsp;<?php echo $last; ?></h6></td>
            <!-- Written Works -->
          <td><input type="text" name="sw1" value="<?php echo $ws1; ?>"></td>
          <td><input type="text" name="sw2" value="<?php echo $ws2; ?>"></td>
          <td><input type="text" name="sw3" value="<?php echo $ws3; ?>"></td>
          <td><input type="text" name="qz1" value="<?php echo $ws4; ?>"></td>
          <td><input type="text" name="qz2" value="<?php echo $ws5; ?>"></td>
       </tr>

       <?php } ?>
     </table>

       <input type="submit" name="submit" value="submit">

</form>

查询保存行:

只有行中列的值相同时才会保存。 请帮我解决这个问题。在此先感谢。

<?php  

    if ($_POST["submit"]) {

       $sw1 = $_POST['sw1'];
       $sw2 = $_POST['sw2'];
       $sw3 = $_POST['sw3'];
       $qz1 = $_POST['qz1'];
       $qz2 = $_POST['qz2'];

       $WST = $sw1 + $sw2 + $sw3 + $qz1 + $qz2; 
       $WSP1 = ($WST / 150 )*100;
       $WSP =  number_format((float)$WSP1, 2, '.', '');


       $sql="UPDATE tbl_quarter1  set sw1 = '$sw1' , sw2 = '$sw2', 
             sw3 = '$sw3', qz1 = '$qz1', qz2 = '$qz2', 
             WST='$WST', WSP='$WSP'";
       mysql_query($sql) or die(mysql_error());
   }
?>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

在表单中,您需要传递 名字 姓氏

<input type="hidden" name="first_name" value="<?php echo $first; ?>" />
<input type="hidden" name="last_name" value="<?php echo $last; ?>" />

在处理脚本中,您可以根据 名字 姓氏

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];

$sql="UPDATE tbl_quarter1  set sw1 = '$sw1' , sw2 = '$sw2',
      sw3 = '$sw3', qz1 = '$qz1', qz2 = '$qz2', WST='$WST', 
      WSP='$WSP' WHERE first_name = '$first_name' AND 
      last_name = '$last_name' ";