更新查询只是更新最后一行并影响其他值的值

时间:2016-05-14 11:41:26

标签: php mysql

<?php
include 'connection.php';  
 ?>
<form action="update.php" method="post">
<?php 
$grp=$_GET['group_num'];
$query = "SELECT * FROM lectures_table WHERE group_num=$grp";
$result = mysql_query($query);

while($row=mysql_fetch_array($result)){   

</div>   
 <input type="hidden" name="group_num" value="<?php echo $grp;  ?>" />
  <input type="text" placeholder="First Lecture" name="day[]" value="<?php             
 echo $row['day']; ?>"></td>
    <input type="text" placeholder="First Lecture" name="f[]" value="<?php      

 echo $row['first']; ?>"></td><br>

 </tr>

 <?php 


 } ?>

</tbody>
 </table>         
   <input type="submit" class="btn btn-success" name="edit" value="save">
  &emsp;&emsp;
 </form>
  </div>
    </div>
     </div>
 </div> ?>
 </body>
  </html>

update.php

    <?php
    include 'connection.php';
     $i = 0; 
   while ($i < 5) { 
   // define each variable 
   $scoreaway = $_POST['f'][$i]; 

   // do the update and print out some info just to provide some visual feedback 
   echo $query = "UPDATE lectures_table SET first='".$scoreaway."' WHERE           
   group_num=1"; 
   mysql_query($query) or die ("Error in query: $query");  

   $i++; 
   }

   mysql_close();  

   ?>

更新查询只更新最后一行。我该怎么办,我非常需要它。

当我提交表单时,所有值都取最后一个输入的值

1 个答案:

答案 0 :(得分:0)

您需要更改表单,以便每行都有一个包含该行ID的隐藏输入。

while($row=mysql_fetch_array($result)){   ?>
<tr>  
    <td><input type="hidden" name="id[]" value="<?php echo $row['id'];  ?>" /></td>
    <td><input type="text" placeholder="First Lecture" name="day[]" value="<?php echo $row['day']; ?>"></td>
    <td><input type="text" placeholder="First Lecture" name="f[]" value="<?php echo $row['first']; ?>"></td>

</tr>
<?php }

然后在UPDATE语句中使用该ID,而不是group_num

foreach ($_POST['id'] as $i => $id) {
    $scoreaway = $_POST['f'][$i];
    $day = $_POST['day'][$i];
    $query = "UPDATE lectures_table 
                SET first='$scoreaway', day = '$day' 
                WHERE id = $id";
    mysql_query($query);
}

此外,您应该从过时的mysql扩展切换到mysqli或PDO,并使用预准备语句。您当前的代码容易受到SQL注入攻击。见How can I prevent SQL injection in PHP?