【问题标题】:Need help inserting multiple records from an html form using PHP/MySQL需要帮助使用 PHP/MySQL 从 html 表单中插入多条记录
【发布时间】:2011-11-20 22:00:09
【问题描述】:

我有一个 PHP 页面,它以 html 表的形式从 MySQL 中的表(成员)生成记录列表。我想要做的是能够检查(使用复选框)我想要使用的记录。当我检查部分/所有记录时,我想添加更多信息(每个成员拥有的共享数)并将这些记录插入另一个表(共享)。两个表(shares & members)共享一个列(member_ID)。

所以,我需要以下帮助:

  1. 如何编码 html 表格以包含复选框以及份额数量的输入字段?

  2. 如何编写为每条检查记录插入一条记录的函数?

我意识到这有很多问题,所以任何帮助我解决这个问题的努力都将不胜感激。

这是我的 [错误] 代码:

HTML 表单:

<form method="post" action="index.php?action=add_shares&org_ID=<?php echo $org_ID; ?>"     id="add_shares
    <table>
    <?php foreach ($members as $members) : ?>
    <tr>
        <td><input id="member_ID" name="member_ID[]" value="'"$members['member_ID']."'" type="checkbox"></td>
        <td><?php echo $members['nick_name']; ?></td>
    </tr>
    <?php endforeach; ?>
</table>
<input type="submit" value="Click to distribute shares" />
</form>

这是我的功能:

function add_share($asset_ID, $member_ID, $percent_owner) {
global $db;
$query = "INSERT INTO shares
            (asset_ID, member_ID, percent_owner)
          VALUES
            ($asset_ID, $member_ID, $percent_owner)";
$add_shares = $db->exec($query);

我相信我需要在我的函数中的某个地方设置一个 foreach。我还认为我需要以某种方式将 html 表单中的所有检查记录收集到一个数组中,然后使用 foreach 对数组中的每条记录进行插入。

谢谢!

【问题讨论】:

  • 到目前为止你能发布你的代码吗?
  • 我有类似的需求,用户必须从 640 张卡片中挑选他拥有的卡片。表单是使用表单中的复选框创建的。我想知道如何编写更新 SQL 语句来获取每个 640 个卡 ID 并将其插入/更新到数据库中。您是如何编写解决方案的?

标签: php mysql foreach


【解决方案1】:

这没有错误检查,并假设平均分配份额。

// Assuming equal distribution of shares...
$percent_owner = 100 / count($_POST['member_ID']);
foreach ($_POST['member_ID'] as $member_ID) {
    add_share($_GET['org_ID'], $member_ID, $percent_owner);
}

我会将actionorg_ID 移动到隐藏的输入标签中,这样您的PHP 变量都可以通过$_POST 变量访问,但这只是我自己。

<form method="post" action="index.php" id="add_shares">
    <input type="hidden" name="org_ID" value="<?php echo $org_ID; ?>" />
    <input type="hidden" name="action" value="add_shares" />
    ...
<!-- in your PHP code $_GET['org_ID'] becomes $_POST['org_ID'] -->

【讨论】:

  • 对于 percent_owner,我希望在我的表单中有一个文本框,以便它可以是一个输入值。我想为每条检查的记录提交 member_ID 和 percent_owner。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多