I am creating an HTML form with repeatable rows. One of the fields in each row (docname1) is a multi-select field.
The problem is that I am only able to access the first selected value of the select field in a given row, but of course, I need to access all of them.
Here is the simplified HTML form and the initial row of repeatable fields:
<table>
<tbody id="TBody">
<tr id="TRow">
<td><select name="country[]" id="country">
<!-- irrelevant population of options -->
</select></td>
<td><select name="state[]" id="state">
<!-- irrelevant population of options -->
</select></td>
<td><input type="text" name="qty[]" id="ccc"></td>
<td><input type="text" name="price1[]" id="ddd"></td>
<td><input type="text" name="discunt[]" id="eee"></td>
<td><input type="text" name="tot4[]" id="fff"></td>
<td><select name="tech1[]" id="ggg">
<!-- irrelevant population of options -->
</select></td>
<td><select name="docname[]" id="iii">
<!-- irrelevant population of options -->
</select></td>
<!-- <select name="docname1[][]" multiple> is the concern: -->
<td><select class="chosen-select" name="docname1[][]" multiple>
<!-- irrelevant population of options -->
</select></td>
<td><input type="text" name="remarks3[]" id="zzz">
<!-- some other irrelevant hidden fields -->
</td>
<td class="NoPrint"><button type="button" onclick="BtnDel(this)">x</button></td>
</tr>
</tbody>
</table>
and below is processing code
if (isset($_POST['submit'])) {
// declare database connection as $con
// 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);
}
implode()call, not the database query.