php中的多重插入

s71maibg  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我的窗体的图形表示
我试图实现的是,当用户单击[submit]时,所有下拉列表和表单选择都必须插入到数据库中。
这是我正在使用的查询:

$sql4 = "INSERT INTO UserRequests(
    `UserId`,
    `ConstituencyId`,
    `RequestCategoryId`,
    `Request`,
    `CreatedOn`
  ) VALUES (
    '" . $_SESSION["userId"] . "',
    '" . $_SESSION["ConstituencyId"] . "',
    '" . $_POST['selection'] . "',
    '" . $_POST['txtTitle'] . "',
    '" . $date . "'
  )";

在表单上,有一个按钮供用户添加和删除表单中的行,因此在提交表单时,没有固定的行长度 $_POST . 如果用户单击该按钮,则会向窗体中添加新行。在那一行,下拉菜单在那里,文本框在那里。如果用户单击submit按钮,所有行数据(包括新添加的表单行)都必须插入到名为userrequests的表中。
我在学习php,我是一个初学者。
如果有5行数据,则将这5行下拉菜单数据和5行文本字段数据插入数据库。请帮忙。谢谢。

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $date = date('Y-m-d H:i:s');
    $sql4 = "INSERT INTO UserRequests(
      `UserId`,
      `ConstituencyId`,
      `RequestCategoryId`,
      `Request`,
      `CreatedOn`
    ) VALUES (
      '" . $_SESSION["userId"] . "',
      '" . $_SESSION["ConstituencyId"] . "',
      '" . $_POST['selection'] . "',
      '" . $_POST['txtTitle'] . "',
      '" . $date . "'
    )";

    $result4 = $conn->query($sql4);
?>

<div class="container">
    <h3 class="text-center">User Requests Section</h3>
        <hr class="horizontal-line">
            <form method="POST" action="">
                <div class="row">
                    <table class="table" id="table">
                        <tr>
                            <td>
                                <select name="selection">
                                <?php
                                    foreach ($result3 as $RequestCategories) 
                                    {
                                ?>
                                    <option value="<?php echo $RequestCategories["Id"]; ?>">
                                    <?php echo $RequestCategories["RequestCategory"]; ?></option>
                                <?php }?>
                            </select>
                        </td>
                        <td>
                            <input type="text" id="txtTitle" name="txtTitle" placeholder="Enter Your Description" required="">
                        </td>
                        <td>
                            <button type="button" class="removebutton" title="Remove this row">Delete</button>
                        </td>
                    </tr>
                </table>
            </div><!-- End of Row -->
            <button type="submit">Submit</button>
        </form>
        <button id="addbutton">Add Row</button>
    </div> <!-- End of Container -->
</div>
<script type="text/javascript">
var i = 1;
$("#addbutton").click(function () {
 $("#table tr:first").clone().find("input").each(function () {
     $(this).val('').attr({
         'id': function (_, id) {
             return id + i
         },
             'name': function (_, name) {
             return name + i
         },
             'value': ''
     });
 }).end().appendTo("#table");
 i++;
 });

 $(document).on('click', 'button.removebutton', function () {
 alert("Delete row");
 $(this).closest('tr').remove();
 return false;
 });
</script>
mzmfm0qo

mzmfm0qo1#

所以,你需要一个 foreach 循环以重复运行查询,因为它可以是未指定的长度。而且,既然你在利用 $_SESSION ,则需要初始化会话。
假设 selection 以及 txtTitle 如果是唯一要发布的字段,则可以使用array\u chunk()将数组拆分为两部分(当然,在取消设置不需要的变量之后)

<?php

    //Initialise the session
    session_start();

    //You have a button "submit" in your post that will mess up this loop.
    //Remove it so it won't be an issue
    if( isset( $_POST['submit'] ) )unset( $_POST['submit'] );

    /**
    * Each row consists of 2 inputs, and so we want to array_chunk($_POST, 2),
    * so that the structure will be as follows:
    *
    *  $_POST = array(
    *      [0] => array(
    *          ["selection"] => "select_value",
    *          ["txtTitle"] => "text_value",
    *        ),
    *      [1] => array(
    *          ["selection"] => "select_value",
    *          ["txtTitle"] => "text_value",
    *        ),
    *    );
    * 
    * But you don't need to know much more than that for now, but arrays _always_ start at 0
    *
  **/
   $values = array_chunk( $_POST, 2 );

   //This is the output
   $output = array();

   //Now that we split up the input, we are left with the rows
   foreach($values as $key=>$row){
       /**
       * Rows will be structured as this
       *
       * $row = array(
       *    ["selection"] => "select_value",
       *    ["txtTitle"] => "text_value",
       *   );
     **/

       $insertQuery = "INSERT INTO UserRequests(
            `UserId`,
            `ConstituencyId`,
            `RequestCategoryId`,
            `Request`,
            `CreatedOn`
          ) VALUES (
            '" . $_SESSION["userId"] . "',
            '" . $_SESSION["ConstituencyId"] . "',
            '" . $_POST['selection'] . "',
            '" . $_POST['txtTitle'] . "',
            '" . $date . "'
          )";

       //Insert this row to the database
       $conn->query($insertQuery);

       //Add the insertion count to an array
       $output[] = $conn->num_rows . " row has been inserted.";
   }

   print_r( $output, 1 );
?>

相关问题