2014-02-07 38 views
-2

我在一个窗体上有一个button.onclick按钮它将添加一个窗体,如果再次按下它将按照需求添加窗体。现在我想要采取所有添加的表单值,并使用php插入到数据库作为一行。以下是使用的代码。获取数组值并将其作为一行插入到数据库

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

试试这个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_queryPDO

+0

请记住,由于安全风险,现在不鼓励'mysql_ *'函数。在所有生产场所,您应该使用PDO或'mysqli'。 –

+0

@BenedictLewis谢谢你的建议。我知道。因为OP没有描述他刚刚使用哪个例子。他可以使用其他任何东西pdo或mysqli,因为他正在使用 –

+0

我明白了,但新用户(尤其是具有1个声望的用户)倾向于复制和粘贴答案,并且从不再检查,因此确保他们知道这是一个例子,不是推荐的解决方案。 –

相关问题