gpt4 book ai didi

php 通过循环更新

转载 作者:行者123 更新时间:2023-11-29 07:39:06 26 4
gpt4 key购买 nike

当用户填写表格时,他们还填写了轴数。提交后,信息将发送到表:“train_information”。行轴是 FK,也被发送到表“轴”中。插入后的工作台轴如下所示:

database 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>

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

现在您所要做的就是在循环中调用 $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();
}

关于php 通过循环更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29601629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com