gpt4 book ai didi

php - 使用一个 PHP 提交按钮更新多个 MySQL 行

转载 作者:行者123 更新时间:2023-11-30 23:29:50 27 4
gpt4 key购买 nike

我很难找出我认为应该很简单的东西。我需要使用一个提交按钮更新数据库中的多行。我现在让它与每一行的提交一起工作,但我需要将它组合起来。这就是我正在尝试的。我哪里出错了? (我一直在学习我在网上找到的多个教程,我想我把所有的东西都搞混了)。

这是表格:

<?php foreach ($teams as $team): 
$id[]=$team['id'];?>


<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>

<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />

<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />

<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />

<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />

<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />

<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />

<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>

这是处理更新的 PHP:

try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}

}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}

header('Location: .');
exit();

提前致谢!

最佳答案

有几件事需要修复。

  1. FORM 必须在 foreach 之外。

  2. '...name="name"value="...',为了与 _POST 代码一致,应该改为: ... 名称="名称"值="...

这样,单个 POST 将提交,比如说,

  name123="Rangers"
mwins174="123"

然后您需要所有 ID。您可以通过在 foreach 中发出以下命令来做到这一点:

 <input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />

这将生成 HTML:

 <input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />

在 $_POST['id'] 中是一个包含 123、456 等的数组。

你也可以输入 HTML:

 <input type="text" name="name[<?php print $team['id']; ?>]" value="...

因此 $_POST['name'] 将是一个向量,其键与 id 的值相同,因此:

foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}

这样您就有一个提交和多个更新。

关于php - 使用一个 PHP 提交按钮更新多个 MySQL 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318727/

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