Javascript 获取数组值并将其作为行插入数据库中
我有一个表单,其中有一个按钮。点击按钮,它将添加一个表单,如果再次按下它,将根据需要添加表单。现在我想采取所有添加的表单值,并插入数据库作为一行使用php。下面是使用的代码 JS代码:-Javascript 获取数组值并将其作为行插入数据库中,javascript,php,mysql,Javascript,Php,Mysql,我有一个表单,其中有一个按钮。点击按钮,它将添加一个表单,如果再次按下它,将根据需要添加表单。现在我想采取所有添加的表单值,并插入数据库作为一行使用php。下面是使用的代码 JS代码:- function addExpertFrom() { var div = document.createElement('div'); div.className = 'expform'; div.innerHTML = '<label class="explabel">Expert Name:
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 );
}
$txtexpname[] = $_POST['txtexpname'];
$txtexplink[] = $_POST['txtexplink'];
$txtreviewtitle[] = $_POST['txtreviewtitle'];
$txtrevdetails[] = $_POST['txtrevdetails'];
这会给我一个数组的计数
foreach ($_POST['txtexpname'] as $key => $expname)
{
$count = $count + 1;
}
现在我该怎么做才能完成这项任务。请帮助我。试试这段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.*
函数。在所有生产站点中,您都应该使用PDO或mysqli
@BenedictLewis谢谢您的建议。我知道。因为OP没有描述他使用的是哪一个,我只是举了个例子。他可以在使用pdo或mysqli时使用其他任何东西。我明白了,但是新用户,特别是那些拥有1个声誉的用户,倾向于复制和粘贴答案,并且从不再次检查,因此确保他们知道这是一个示例,而不是推荐的解决方案非常重要。@BenedictLewis现在可以了吗?