php 通过循环更新

php Update via loop

当用户填写表格时,他们还会填写车轴数。提交后,信息会发送到 table: "train_information"。排轴是 FK,也可以在 table "axle" 中发送。 table 轴插入后如下所示:

现在我希望能够更新距离(现在是 NULL)。 我通过显示轴数并制作一个字段框来做到这一点:

                 <tr> 
                    <?php      
                        foreach($show_axle as $axleposition){ ?>
                        <input type='hidden' name='axle_id' value='<?php echo $axleposition['axle_id']?>'>
                        <td><input type='text' name='distance' id = "<?php echo $axleposition['axle_id']?>"placeholder="<?php echo $axleposition['axle']?>"></td>

                        <?php
                        } 
                    ?>
                </tr>

如您所见,我以表格形式展示了它。表单操作是:

<form method='POST' action='axle_update.php'>

所以当他们按下提交时,他们会转到 axle_update.php,看起来像这样:

<?php
    ?><pre><?php print_r($_POST) ?> </pre> <?php 

    $update_axle = $database->update_axles();
?>

(pre是给自己看发什么的)

这有点管用。因为当我有例如 12 行时(见图)。它只更新最后一行。现在这是因为隐藏字段的名称在任何地方都是相同的。但我不知道如何更改它(在查询中)。

编辑:

抱歉忘了 update_axles:

function update_axles() {
        $sql = "UPDATE axle SET distance = :distance WHERE axle_id = :axle_id";
        $sth = $this->pdo->prepare($sql);
        $sth->bindParam(':axle_id', $_POST['axle_id'], PDO::PARAM_INT);
        $sth->bindParam(":distance", $_POST['distance'], PDO::PARAM_STR);
        $sth->execute();
    }

每次您添加另一个输入时,您的输入都会被覆盖。

要解决这个问题,请使用输入数组。如下;

<tr> 
<?php      
  foreach($show_axle as $axleposition){ ?>
       <input type='hidden' name='axle_id[<?php echo $axleposition['axle_id']?>]' value='<?php echo $axleposition['axle_id']?>'>
       <td><input type='text' name='distance[<?php echo $axleposition['axle_id']?>]' id = "<?php echo $axleposition['axle_id']?>"placeholder="<?php echo $axleposition['axle']?>"></td>
<?php
  } 
?>
</tr>

现在,当您 POST 表单时,您将拥有一个关联数组。

现在您所要做的就是循环调用 $database->update_axles(),传递 ID 和值。

注意:根据您输入的大小,不要将其传递到循环中,因为不建议在循环中查询!

foreach($_POST['axle_id'] as $id) {
    $update_axle = $database->update_axles($id);
}

最后,更改您的方法以接受这些参数,并修改您的查询。

function update_axles($id) {
  $sql = "UPDATE axle SET distance = :distance WHERE axle_id = :axle_id";
  $sth = $this->pdo->prepare($sql);
  $sth->bindParam(':axle_id', $id, PDO::PARAM_INT);
  $sth->bindParam(":distance", $_POST['distance'][$id], PDO::PARAM_STR);
  $sth->execute();
}