【问题标题】:How to relate the answers and questions in a dynamic form in php?如何在php中以动态形式关联答案和问题?
【发布时间】:2020-08-24 13:12:28
【问题描述】:

我想在 php 中创建一个动态表单构建器,类似于 Google 表单,但我在将答案和问题关联到同一个表单时遇到了问题。我不想为每个问题制作一个表格并将答案联系起来。我想要一个包含所有问题的表单,当我单击保存按钮时,答案将与相应的 question_id 一起保存。

我应该创建隐藏输入来发送每个 question_id 吗?

最好的方法是什么?

数据库设计

源代码:

<form action="form.php">
<?php foreach ($questions as $question): ?>
    <div>
        <label><?= $question["title"] ?></label>
        <input type="hidden" name="question_id" value="<?= $question["id"] ?>">

        <?php if ($question["type"] == "text"): ?>
            <input type="text" name="answer_text">
        </div>
        <?php elseif ($question["type"] == "select"): ?>
        <select name="areas">
            <?php foreach ($options as $option): ?>
                <option value="<?= $option["text"] ?>"><?= $option["text"] ?>
            <?php endforeach ?>
        </select>
        <?php endif ?>
    </div>
<?php endforeach ?>

<button type="submit">Send</button>

</form>

【问题讨论】:

    标签: php html database


    【解决方案1】:

    您可以通过将[] 添加到参数名称来将数组添加到表单(和URL 查询参数)。这样您将在form.php 中收到一个数字数组。

    您还可以指定您的密钥:

    <form action="form.php">
        <?php
        foreach ($questions as $question):
            $qid = $question["id"];
        ?>
        <div>
            <label><?= $question["title"] ?></label>
            <input type="hidden"
                name="types[<?php echo htmlentities($qid) ?>]"
                value="<?= $question["type"] ?>" />
    
            <?php if ($question["type"] == "text"): ?>
                <input type="text"
                    name="answer_text[<?php echo htmlentities($qid) ?>]" />
            <?php elseif ($question["type"] == "select"): ?>
                <select
                    name="areas[<?php echo htmlentities($qid) ?>]">
                    <?php foreach ($options as $option): ?>
                        <option value="<?= $option["text"] ?>"><?= $option["text"] ?>
                    <?php endforeach ?>
                </select>
            <?php endif ?>
        </div>
        <?php endforeach ?>
    
        <button type="submit">Send</button>
    </form>
    

    如果您 100% 确定问题 ID 不会包含任何奇怪的字符,则可以删除 htmlentities()s。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多