我有一个HTML表单,允许用户使用JavaScript临时添加行。
表格:
<form method="post" action="send.php">
<table id="table">
<tr><th>job</th><th>comment</th></tr>
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
<tr>
</table>
<input type ="button" value="add entry" onclick="add('table')"/>
<input type ="submit" id="submit" value="submit"/>
JavaScript:
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.type = "text";
newcell.appendChild(newentry);
}
}
PHP代码
$job = $_POST['job'];
$comment = $_POST['comment'];
//code to connect to database
$add_stmt = $mysqli->prepare("INSERT INTO job (job, comment) VALUES (?, ?)");
$foreach($job as $a => $b) {
$add_stmt->bind_param("ss", $job[$a], $comment[$a]);
$add_stmt->execute();
}
当我点击“添加条目”按钮时,将成功创建一行。但是,只有第一行中的数据才会提交给数据库。使用
echo "row count is" . count($_POST['job']);
即使我有几行数据,我的“行数为1”。 有人可以弄清楚我的代码可能出了什么问题吗?非常感谢!
答案 0 :(得分:1)
您必须为添加的字段设置名称属性:
// create array with names
var names = ['job[]', 'comment[]'];
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.type = "text";
// set name
newentry.name = names[i];
newcell.appendChild(newentry);
}
}
您可以尝试制作两个文件:index.html和send.php并插入此内容:
的index.html:
<html>
<head>
<script>
var names = ["job[]", "comment[]"];
function add(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
var newentry = document.createElement('textarea');
newentry.name = names[i];
newentry.type = "text";
newcell.appendChild(newentry);
}
}
</script>
</head>
<body>
<form method="post" action="send.php">
<table id="table">
<tr><th>job</th><th>comment</th></tr>
<tr>
<td><textarea name = "job[]"></textarea></td>
<td><textarea name = "comment[]"></textarea></td>
<tr>
</table>
<input type ="button" value="add entry" onclick="add('table')"/>
<input type ="submit" id="submit" value="submit"/>
</form>
</body>
</html>
send.php:
<?php
$job = $_POST['job'];
$comment = $_POST['comment'];
var_dump($job);
var_dump($comment);
?>
在你的服务器上运行 - 这对我有用。确保正确设置了名称。