Docname[]][] storing just single value instead of multi value

I am trying to store multiple value in dynamic created row in php form, everything is working fine but processing code only storing just first value into mysql table rather than all multi selected value. below is my code

 <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[][]"  id="iii" multiple  required onfocus="Calc(this);">
	<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>

Processing code

<?php

if (isset($_POST['submit'])) {
    // getting all values from the HTML form
}

// database details
$host = "localhost";
$username = "oot";
$password = "agghhj";
$dbname = "hmis";

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

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

// Process each set of form inputs
for ($i = 0; $i < count($_POST['city']); $i++) {
    // Check if docname1 is set and convert it to a comma-separated string
    $docname1Array = isset($_POST['docname1']) ? $_POST['docname1'] : [];
    $docname1 = isset($docname1Array[$i]) ? implode(',', (array) $docname1Array[$i]) : '';

    $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]);

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

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

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

// close the connection
mysqli_close($con);
?>

even array is showing two values, but still storing just first one in mysql table
Array
(
[country] => Array
(
[0] => 2
)

[state] => Array
    (
        [0] => 2
    )

[city] => Array
    (
        [0] => 3
    )

[qty] => Array
    (
        [0] => 1
    )

[price1] => Array
    (
        [0] => 150
    )

[discunt] => Array
    (
        [0] => 0
    )

[tot4] => Array
    (
        [0] => 150
    )

[tech1] => Array
    (
        [0] => Shahid Jameel
    )

[docname] => Array
    (
        [0] => Team B
    )

[docname1] => Array
    (
        [0] => Array
            (
                [0] => OT One
            )

        [1] => Array
            (
                [0] => OT Two
            )

    )

[remarks3] => Array
    (
        [0] => 
    )

[remarks4] => Array
    (
        [0] => 
    )

[zzz1] => Array
    (
        [0] => 0
    )

[zzz2] => Array
    (
        [0] => 0
    )

[zzz3] => Array
    (
        [0] => 0
    )

[zzz4] => Array
    (
        [0] => 0
    )

[zzz5] => Array
    (
        [0] => 0
    )

[submit] => Submit

)

No. Those are two separate arrays. Not an array with two elements.

For this to work for dynamically added, multiple option select menus, you need to explicitly give the 1st array key a value, e.g. name="docname1[0][]" And increment that value for each dynamically added set of form fields.

done thanks for the help

function BtnAdd() {
    // Destroy any existing chosen select elements
    $('.chosen-select').chosen('destroy');
    
    // Clone the row template and append it to the tbody
    var rowCount = $('#TBody tr').length; // Count the number of rows in tbody
    var v = $('#TRow').clone().appendTo('#TBody');
    
    // Remove id and d-none class from the cloned row
    $(v).removeAttr('id').removeClass('d-none');
    
    // Update input names with unique indices
    $(v).find('input').each(function() {
        var name = $(this).attr('name');
        if (name) {
            var newName = name.replace(/\[\d+\]/, '[' + rowCount + ']'); // Replace the first array index with the new index
            $(this).attr('name', newName);
        }
    });
    
    // Update select names with unique indices
    $(v).find('select').each(function() {
        var name = $(this).attr('name');
        if (name) {
            var newName = name.replace(/\[\d+\]/, '[' + rowCount + ']'); // Replace the first array index with the new index
            $(this).attr('name', newName);
        }
    });
    
    // Initialize Chosen plugin for new selects
    $('.chosen-select').chosen({width: '100%'});
    
    // Clear input values in the cloned row
    $(v).find("input").val('');
    
    // Initialize autocomplete if needed
    $(v).find("input").autocomplete({
        source: 'backend-script.php'  
    });
    
    // Update the row number in the first <th> element
    $(v).find("th").first().html(rowCount + 1);
}

I recommend that you test this by deleting a row that isn’t the last row, then adding a new row. The previous last row will get moved up and the new row will end up with the same array index as the previous last row.

You should instead initialize a js variable, before the start of the BtnAdd function, use it as the array index for the dynamically added fields, then increment it.

yes i done this by. but it again store all selected value in first row in mysql rather than in each row.

// Declare a global counter variable
var rowCounter = 0;

function BtnAdd() {
   // Destroy any existing chosen select elements
   $('.chosen-select').chosen('destroy');
   
   // Clone the row template and append it to the tbody
   var v = $('#TRow').clone().appendTo('#TBody');
   
   // Remove id and d-none class from the cloned row
   $(v).removeAttr('id').removeClass('d-none');
   
   // Update input names with unique indices
   $(v).find('input').each(function() {
       var name = $(this).attr('name');
       if (name) {
           var newName = name.replace(/\[\d+\]/, '[' + rowCounter + ']'); // Replace the index with the new counter value
           $(this).attr('name', newName);
       }
   });
   
   // Update select names with unique indices
   $(v).find('select').each(function() {
       var name = $(this).attr('name');
       if (name) {
           var newName = name.replace(/\[\d+\]/, '[' + rowCounter + ']'); // Replace the index with the new counter value
           $(this).attr('name', newName);
       }
   });
   
   // Initialize Chosen plugin for new selects
   $('.chosen-select').chosen({width: '100%'});
   
   // Clear input values in the cloned row
   $(v).find("input").val('');
   
   // Initialize autocomplete if needed
   $(v).find("input").autocomplete({
       source: 'backend-script.php'  
   });
   
   // Update the row number in the first <th> element
   $(v).find("th").first().html(rowCounter + 1);
   
   // Increment the rowCounter for the next addition
   rowCounter++;
}

What does print_r($_POST) show?

The set of form fields output on the page should have a [0] index. The index for the dynamically added fields should start at 1.