我正在尝试将数据从html表单保存到MySQL数据库。我是Web开发人员和javascript的新手。我有一种表单,用户可以根据需要添加多少行来添加行字段。表单可以成功添加和删除行,但是问题是检索所有行字段。当我在form_process php文件中使用$ _POST时,我只能访问最后一行的详细信息。如何检索用户将创建的所有行字段,以便将其保存到数据库?
我尝试了这些帖子,但它们不处理动态表单字段:规范:如何将HTML表单数据保存到MySQL数据库中以及动态表单字段的创建和保存在数据库php中mysql
下图显示了具有3行字段的表单。如何检索所有行值,以便将它们保存到MySQL数据库的表中?非常感谢您提前抽出宝贵的时间
我的HTML表单代码如下:
<fieldset class="row2">
<legend>Bus Data</legend>
<p>
<input type="button" value="Add Bus" onClick="addRow('busDataTable')" />
<input type="button" value="Remove Bus" onClick="deleteRow('busDataTable')" />
<p>(Remove action applies only to a column with a marked check box.)</p>
<p>
<table id="busDataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Bus #</label>
<input type="text" required="required" name="Bus_Number">
</td>
<td>
<label for="Load_kW">Load kW</label>
<input type="text" required="required" name="Load_kW">
</td>
<td>
<label for="Load_kVAR">Load kVAR</label>
<input type="text" required="required" name="Load_kVAR">
</td>
<td>
<label for="Voltage_kV">Voltage kV</label>
<input type="text" required="required" name="Voltage_kV">
</td>
</p>
</tr>
</tbody>
</table>
我的PHP代码应该处理该表单:(这里的主要问题是,我可以检索单行,但如何检索所有行?
<?php
// put your code here
// Connecting to mySQL database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Radial Distribution System";
// Create connection to database and get power system data
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // for showing the exact error on the html page
$conn = new mysqli($servername, $username, $password, $dbname);
$_busNumber = array();
$_busNumber []= $_POST['Bus_Number'];
print_r($_busNumber);
$conn->close();
?>
创建/添加额外行的javascript代码:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 66){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum nodes for this platform is 66.");
}
}
您可以通过添加[]
到末尾来定义要在PHP中作为数组填充的HTML表单字段。
<input type="text" required="required" name="Bus_Number[]">
上面的代码将导致在$_POST['Bus_Number']
PHP中创建一个数组,您可以从那里进行处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句