我有一个HTML表格和一个允许用户添加多行的按钮。
<table id="component_table">
<thead>
<tr>
<th>Component</th>
<th>Component Type</th>
<th>Component Thickness</th>
</tr>
</thead>
<tbody id="component_tb">
<tr>
<td><?php echo $roofComponentDropDown ?></td>
<td><?php echo $roofComponentTypeDropDown ?></td>
<td><input id="component_thickness" name="component_thickness" type="text"></td>
</tr>
</tbody>
</table>
<input type="button" value="+" id="addRows" />
这些是我为表格生成的下拉列表
//Queries here to get data for the drop down lists that make up the roof construction table...
$roofComponentQuery = "SELECT * FROM roof_component";
$roofComponentData = mysqli_query($dbc, $roofComponentQuery);
while ($rcRow = mysqli_fetch_array($roofComponentData)) {
$roofComponentOptions .="<option value=\"".$rcRow['roof_component_id']."\">" . $rcRow['roof_component_name'] . "</option>";
}
$roofComponentDropDown = "<select name='selectedRoofComponent' id='selectedRoofComponent' onChange='getComponentType(this)'>
<option selected='selected' disabled='disabled' value=''>Select Component</option>
" . $roofComponentOptions . "
</select></br>";
$roofComponentTypeDropDown = "<select name='selectedComponentType' id='selectedComponentType'>
<option class='toggle_control' selected='selected' disabled='disabled' value=''>Select Type</option>
</select></br>";
有没有办法将每个<tr>
添加到数组中,然后使用foreach循环遍历数组并将每个<tr>
插入数据库?
这样的事可能吗?
$tableRow = array();
foreach ($tableRow as $row) {
//insert query
}
答案 0 :(得分:1)
将<select>
元素名称以[]
结尾。
$roofComponentDropDown = "<select name='selectedRoofComponent[]' id='selectedRoofComponent' onChange='getComponentType(this)'>
<option selected='selected' disabled='disabled' value=''>Select Component</option>
" . $roofComponentOptions . "
</select></br>";
$roofComponentTypeDropDown = "<select name='selectedComponentType[]' id='selectedComponentType'>
<option class='toggle_control' selected='selected' disabled='disabled' value=''>Select Type</option>
</select></br>";
然后$_POST
的元素将是你可以循环的数组。
foreach ($_POST['selectedRoofComponent'] as $index => $component) {
$componentType = $_POST['selectedComponentType'][$index];
// INSERT $component and $componentType into database
}
答案 1 :(得分:0)
首先确保每个<tr>
以及随后新创建的<tr>
都有唯一的行ID。然后使用它来为每个<td>
中与表单一起提交的元素创建数组索引分配名称。
或许像<select name='tableRow[rowId][selectedRoofComponent]' id='selectedRoofComponent' onChange='getComponentType(this)'>
这样的东西应该会在POST数据中为你提供一个具有相应结构的数组。
rowId
需要是一个变量,它可以由您的javascript生成,也可以在页面加载时由php呈现。所以在php中它可能看起来像:
"<select name='tableRow[" . $rowId . "][selectedRoofComponent]' id='selectedRoofComponent' onChange='getComponentType(this)'>"
或javascript
"<select name='tableRow[" + rowId + "][selectedRoofComponent]' id='selectedRoofComponent' onChange='getComponentType(this)'>"
为了给你提供比这更具体的东西我还需要看到javascript。