我在一个表单上有一个按钮。单击按钮它会添加一个表单如果再按一次将根据要求添加表单。现在我想要获取所有添加的表单值并插入到DB中使用php.Following的行是使用过的代码。
JS代码: -
function addExpertFrom()
{
var div = document.createElement('div');
div.className = 'expform';
div.innerHTML = '<label class="explabel">Expert Name: </label><input type="text" id="txtexpname" name="txtexpname[]" class="expfield" placeholder="Enter name of expert"/>\
<div class="clearboth"></div>\
<label class="explabel">Link of the expert work: </label><input type="text" id="txtexplink" name="txtexplink[]" class="expfield" placeholder="Enter link of expert work"/>\
<div class="clearboth"></div>\
<label class="explabel">Title of the review: </label><input type="text" id="txtreviewtitle" name="txtreviewtitle[]" class="expfield" placeholder="Enter title of review"/>\
<div class="clearboth"></div>\
<label class="explabel">Details of the review: </label><input type="text" id="txtrevdetails" name="txtrevdetails[]" class="expfield" placeholder="Enter details of review"/>\
<div class="clearboth"></div>\
<input type="button" class="btn btn-primary" value="Remove" onclick="removeForm(this)">\
<div class="line"></div>';
document.getElementById('expertform').appendChild(div);
}
function removeForm(input)
{
document.getElementById('expertform').removeChild( input.parentNode );
}
PHP代码: -
$txtexpname[] = $_POST['txtexpname'];
$txtexplink[] = $_POST['txtexplink'];
$txtreviewtitle[] = $_POST['txtreviewtitle'];
$txtrevdetails[] = $_POST['txtrevdetails'];
这个wiil给了我一个数组
foreach ($_POST['txtexpname'] as $key => $expname)
{
$count = $count + 1;
}
现在我该怎么做才能完成这项任务。帮助我。
答案 0 :(得分:0)
试试这个PHP代码
<?php
$arr_txtexpname = $_POST['txtexpname'];
$arr_txtexplink = $_POST['txtexplink'];
$arr_txtreviewtitle = $_POST['txtreviewtitle'];
$arr_txtrevdetails = $_POST['txtrevdetails'];
$sizeof_array = sizeof($arr_txtexpname);
for($i=0; $i<$sizeof_array; $i++)
{
$txtexpname = mysql_real_escape_string($arr_txtexpname[$i]);
$txtexplink = mysql_real_escape_string($arr_txtexplink[$i]);
$txtreviewtitle = mysql_real_escape_string($arr_txtreviewtitle[$i]);
$txtrevdetails = mysql_real_escape_string($arr_txtrevdetails[$i]);
// insert here each row
mysql_query("INSERT INTO `your_table`(`field1`, `field2`, `field3`, `field4`) VALUES('$txtexpname', '$txtexplink', '$txtreviewtitle', '$txtrevdetails')") or die(mysql_error());
}
?>
注意:
我使用函数mysql_query
作为示例来插入行。您必须根据项目中的要求使用mysqli_query
或PDO
。