2014-02-07 36 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個聲望的用戶)傾向於複製和粘貼答案,並且從不再檢查,因此確保他們知道這是一個例子,不是推薦的解決方案。 –

相關問題