提交和访问可重复的多选字段值

问题描述 投票:0回答:2

我正在创建动态多行以将数据存储到数据库中。当创建的行以及在

docname1
字段中选择的多个值时,所有工作都在前端正常工作。但问题是,当我处理代码时,它成功保存数据,但 docname1 仅存储第一个值,而不是多个选定的值。

这是php代码

<table class="table table-bordered">
                    <thead class="table-success" style="background-color: #3fbbc0;">
                      <tr>
                     <th width="10%"><center>Service</th>
                        <th width="10%"><center>Type</th>
                        <th width="10%"><center>Consultant</th>
            
            <th width="10%"><center>Qty/Graf.</th>                       
            <th width="10%"><center>Rate/Unit</th>
            <th width="10%"><center>Discount</th>           
            <th width="10%"><center>Total</th>
            <th width="10%"><center>Reff. By</th>
                        <th width="10%"><center>Asst By</th> 
                       <th width="10%"><center>OT</th> 
            <th width="10%"><center>Remarks</th>
            <th width="5%"></th>

                                               
                         <button type="button" class="btn btn-sm btn-success" onclick="BtnAdd()">Add Item</button>                         
                        </th>
</tr>
                    </thead>
                    <tbody id="TBody">
                      <tr id="TRow" class="d-none">



   <td><Select  class="country form-control text-end" name="country[]" id = "country"  required>
<option value=""> Select Service</option>
                <?php
                include('db1.php');
                $query = "select * from country";
                // $query = mysqli_query($con, $qr);
                $result = $con->query($query);
                if ($result->num_rows > 0) {
                    while ($row = mysqli_fetch_assoc($result)) {
                ?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                <?php
                    }
                }     ?>    </select> </td>

              

 <td><Select  class="state form-control text-end" name="state[]" id = "state" required>

<option value="">select Type</option></select></td>
 <td><Select  class="city form-control text-end" name="city[]" id = "city" required onchange="GetDetail(this.closest('tr'))" >

<option value="">Select Cons</option></select></td>
            

 
            
        <td><input type="text" class="qty form-control text-end" name="qty[]" id="ccc" onchange="Calc(this);"  Required></td>
    <td><input type="text" class="price form-control text-end" name="price1[]" id="ddd"   onfocus="Calc(this);" readonly style="background-color: #3fbbc0;"></td>
    <td><input type="text" class="discunt form-control text-end" name="discunt[]"  id="eee" onchange="Calc(this);"  ></td>
    <td><input type="text" class="tot4 form-control text-end" name="tot4[]" id="fff" oninput="Calc(this);"  Required readonly style="background-color: #3fbbc0;"></td>                  
       <td><Select class="form-control text-end" name="tech1[]" id="ggg" Required onfocus="Calc(this);">
       <option value="">Select Reff</option>
         <?php
         include('db.php');
        $sql = mysqli_query($con,"SELECT * FROM reff");
         while($row=mysqli_fetch_array($sql))
        {
         echo '<option value="'.$row['reffered'].'">'.$row['reffered'].'</option>';
          } ?>
           </select></td>

        <td><Select class="form-control text-end" name="docname[]" id="iii" required onfocus="Calc(this);">
    <option value="">Select Asst</option>
        <?php
        include('db.php');
      $sql = mysqli_query($con,"SELECT * FROM tech1");
        while($row=mysqli_fetch_array($sql))
         {
         echo '<option value="'.$row['techname'].'">'.$row['techname'].'</option>';
            } ?>  </select></td>

    <td> <select class="form-control text-end chosen-select" name="docname1[][]" multiple required>
    <option value="">Select OT</option>
        <?php
        include('db.php');
      $sql = mysqli_query($con,"SELECT * FROM mmmach");
        while($row=mysqli_fetch_array($sql))
         {
         echo '<option value="'.$row['mach1'].'">'.$row['mach1'].'</option>';
            } ?>  </select></td>


<td><input type="text" class="form-control text-end" name="remarks3[]"  id="zzz" >
         <input type="hidden" class="form-control text-end mop" name="remarks4[]"  id="zzz9" ><input type="hidden" class="zzz1 form-control text-end" name="zzz1[]"  id="zzz1" ><input type="hidden" class="zzz2 form-control text-end" name="zzz2[]"  id="zzz2" ><input type="hidden" class="zzz3 form-control text-end" name="zzz3[]"  id="zzz3" ><input type="hidden" class="zzz4 form-control text-end" name="zzz4[]"  id="zzz4" ><input type="hidden" class="zzz5 form-control text-end" name="zzz5[]"  id="zzz5" ></td>
        <td class="NoPrint"><button type="button" class="btn btn-success"  style="line-height: 1;" onclick="BtnDel(this)">x</button></td>
            
                      </tr>   </tbody> </table>

下面是处理代码

<?php

if (isset($_POST['submit'])) {
    // Database details
    $host = "localhost";
    $username = "uuuuui";
    $password = "899999";
    $dbname = "uuii";

    // Creating a connection
    $con = mysqli_connect($host, $username, $password, $dbname);

    // Ensure the connection is made
    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // Process each set of form inputs
    $numRows = count($_POST['city']);  // Get the number of rows

    for ($i = 0; $i < $numRows; $i++) {
        // Handle multi-select field docname1
        $docname1Array = isset($_POST['docname1'][$i]) ? $_POST['docname1'][$i] : [];
        $docname1 = implode(',', (array) $docname1Array);

        // Retrieve and sanitize form inputs
        $country = mysqli_real_escape_string($con, $_POST['country'][$i]);
        $state = mysqli_real_escape_string($con, $_POST['state'][$i]);
        $city = mysqli_real_escape_string($con, $_POST['city'][$i]);
        $qty = mysqli_real_escape_string($con, $_POST['qty'][$i]);
        $price1 = mysqli_real_escape_string($con, $_POST['price1'][$i]);
        $tot4 = mysqli_real_escape_string($con, $_POST['tot4'][$i]);

        // Prepare SQL statement
        $sqlInsertItem = "
            INSERT INTO iap44 (country, state, city, qty, price1, tot4, docname1) 
            VALUES ('$country', '$state', '$city', '$qty', '$price1', '$tot4', '$docname1')";
        
        // Execute SQL statement
        $rs1 = mysqli_query($con, $sqlInsertItem);

        if (!$rs1) {
            echo "Error: " . mysqli_error($con);
        }
    }

    // Debugging output
    echo "<pre>";
    print_r($_POST);    
    echo "</pre>";

    // Close the connection
    mysqli_close($con);
}
?>

php forms multidimensional-array multi-select uirepeat
2个回答
0
投票

您遇到的问题显然是有问题的。 在 https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple 进行实验(我不知道还有什么地方可以轻松在线复制),在表单中使用

cars[][]
,选择几个选项,然后提交。

您将看到您的

name = "docname1[][]"
多选方法会将每个选定的值提交为
docname[][]=foo&docname[][]=bar

每次使用空大括号时(在数组的任何级别上,PHP 都会自动递增该元素的索引。因为您使用的是双空大括号,这实际上意味着每个值将被推送到下一个可用的父级别索引和下一个可用的二级索引(在这种情况下,它始终是新创建的父级的

0
索引)。

基本示例:https://3v4l.org/5ggSY

$_POST['docname1'][][] = 'one';
$_POST['docname1'][][] = 'two';
$_POST['docname1'][][] = 'three';
var_export($_POST);

输出:

array (
  'docname1' => 
  array (
    0 => 
    array (
      0 => 'one',
    ),
    1 => 
    array (
      0 => 'two',
    ),
    2 => 
    array (
      0 => 'three',
    ),
  ),
)

由于这一固有的挑战,您的动态/可重复字段应该在父级别上明确键入。 否则,您将无法跟踪哪个多选值属于哪组其他字段。

如果这些字段组是可重复的,则您必须唯一

id
HTML 文档的每个元素才能使其有效。 名称也将类似于
city[$i]
docname[$i][]

纠正 HTML 表单后,实现准备好的语句并执行循环插入查询就很简单了。 请参阅https://stackoverflow.com/a/60178576/2943403,了解仅准备和绑定一次,然后在循环内执行语句的基本形式。 根据您的 PHP 版本,您可能希望更改语法。

if (!empty($_POST['city'])) {
    $stmt = $con->prepare("
        INSERT INTO iap44 (country, state, city, qty, price1, tot4, docname1) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    foreach ($_POST['city'] as $i => $city) {
        // perform validation and sanitization before executing
        $stmt->execute([
            $_POST['country'][$i],
            $_POST['state'][$i],
            $city,
            $_POST['qty'][$i],
            $_POST['price1'][$i],
            $_POST['tot4'][$i],
            implode(',', $_POST['docname1'][$i])
        ]);
    }
}

还有许多其他改进值得推荐,但我会在这些重要部分划清界限。


-1
投票

如果您没有国家、州和城市的多个值,请尝试执行以下操作:

  1. 使用如下名称属性:
    country
    state
    city
    分别代替
    country[]
    state[]
    city[]
  2. 使用
    docname1
    的名称属性,如下所示
    docname1[]
  3. 仅针对一个更改的值多次存储相同的记录并不是一个好习惯,因此您可以做的是创建另一个表并存储
    docname1
    所有值以及
    iap4
    插入记录的外键。为此,您可以使用以下方法:
if (isset($_POST['submit'])) {
  $country = $_POST['country'];
  $state = $_POST['state'];
  $city = $_POST['city'];
  $docname1 = $_POST['docname1'];

  $sqlInsertItem = "INSERT INTO iap4 (country, state, city) VALUES ('$country', '$state', '$city')";

  if (mysqli_query($con, $sqlInsertItem)) {
    $iap4_id = mysqli_insert_id($con);

    foreach ($docname1 as $docname) {
      $sqlInsertDoc = "INSERT INTO doc_names (iap4_id, docname) VALUES ('$iap4_id', '$docname')";

      if (!mysqli_query($con, $sqlInsertDoc)) {
        echo "Error inserting docname: " . mysqli_error($con);
      }
    }
  } else {
    echo "Error inserting item: " . mysqli_error($con);
  }
}
  1. 如果这不是您所需要的,并且您想继续使用单个表插入记录,那么您应该考虑以下事项,这可能会导致问题:

i) 您在这里关闭了表单提交条件,这是不正确的。您应该在记录插入逻辑结束处关闭此括号。

$docname1 = $_POST['docname1']; // Multidimensional array
}

ii)您使用了条件来计算城市并插入记录,我认为这是错误的。因为可能只选择了一个城市,所以它只会执行一次。因此,请在有效属性上使用条件。

for ($i = 0; $i < count($city); $i++) {
© www.soinside.com 2019 - 2024. All rights reserved.