2017-04-10 34 views
0

我需要更新2列92行在具有前端HTML和后端PHP的MySQL表中具有唯一值。请注意,所有行都有唯一的ID。我认为,它可以使用循环轻松完成。但我不熟悉循环,因为我对这个领域很陌生。如何更新92行MySQL列中的2列

这可能是一个重复的问题,但我没有从重复问题中得到任何适当的解决方案。这是我发布这个。

这里是我的前端部分:

<table> 
       <thead> 
       <tr> 
        <th>ID</th> 
        <th>Column 2</th> 
        <th>Column 3</th> 
        <th>Column 4</th> 
       </tr> 
       </thead> 

       <tbody> 

     <form method="post" action="process.php"> 

     <?php 
     $stmt = $mysqli->prepare("SELECT id,column2,column3,column4 FROM records"); 
     $stmt->execute(); 
     $stmt->store_result(); 
     $stmt->bind_result($id,$column2,$column3,$column4); 
     while ($stmt->fetch()) { 

      ?> 
       <tr> 
        <td><?php echo $id ?></td> 
        <td><?php echo $column2 ?></td> 

        <!-- Here User will input values for the below two fields in all the 92 rows --> 

        <td><input type="text" name="column3[<?php echo $id; ?>]"/></td> 
        <td><input type="text" name="column4[<?php echo $id; ?>]"/></td> 


       </tr> 
     <?php } ?> 
       <input type="submit" name="submit" value="Update all"> 
       </form> 
       </tbody> 

    </table> 

如果有人能指导我我怎么更新“栏3”,并在一旦所有的行“column4”领域,我将不胜感激。

process.php

<?php 
if(isset($_POST['submit'])){ 

     foreach($_POST['column3'] as $key=>$value AND $_POST['column4'] as $key=>$value1){ 

      $stmt = $mysqli->prepare("UPDATE records SET column3 = ?, column4 = ? WHERE id = ?"); 
      $stmt->bind_param('sss',$value,$value1,$key); 
      $stmt->execute(); 

     } 

     if ($stmt->execute()) { 
      echo "Done!"; 
      exit(); 
     } 

} 

?> 
+0

是否所有的92行有相同的ID?哪些列获得随机值? – chris85

+0

@ chris85不,所有行都有唯一的ID。我没有得到你的第二个问题。 –

+0

随机值进入'column3'和'column4'吗?你的'WHERE id =?'限制更新为一行......或者你想在更新这一行后更新所有其他行吗? – chris85

回答

0

考虑使用隐藏数组输入字段的值作为ID在HTML形式UPDATE查询以后需要。这样用户就不会看到它或影响它。然后在提交时,遍历$_POST数组的count

HTML(在while循环)

<td><input type="text" name="column3[]"></td> 
<td><input type="text" name="column4[]"></td> 
<input type="hidden" name="hiddenfield[]" value="<?php echo $id; ?>"> 

PHP

if(isset($_POST['submit'])){ 

    for ($i = 0; $i < count($_POST['hiddenfield']); $i++) { 
    $key = $_POST['hiddenfield'][$i]; 
    $value1 = $_POST['column3'][$i]; 
    $value2 = $_POST['column4'][$i]; 

    $stmt = $mysqli->prepare("UPDATE records SET column3 = ?, column4 = ? WHERE id = ?"); 
    $stmt->bind_param('sss', $value1, $value2, $key); 
    $stmt->execute(); 
    } 

    if ($stmt->execute()) { 
     echo "Done!"; 
     exit(); 
    } 
}