2012-04-19 80 views
2

我一直在嘗試這個,但沒有成功。我正在使用PHP,HTML,JavaScript和MySQL。這裏是我的HTML代碼:如何將動態添加的文本框(JavaScript)中的多個數據保存到MySQL數據庫中?

<div id="Author"> 
    <LI>Author</LI> 
    <input type = "text" name="Author[]" value = "1. "/> 
    <input type="button" value="+" id="Authorbutton" onclick="addAuthor()" /> 
</div> 

如果添加按鈕被點擊,另一個文本框會出現,用戶和另一個名字。這裏是我的JavaScript:

var counter3 = 0; 
function addAuthor() { 
    // Get the main Div in which all the other divs will be added 
    var mainContainer = document.getElementById('Author'); 

    // Create a new div for holding text and button input elements 
    var newDiv = document.createElement('div'); 

    // Create a new text input 
    var newText = document.createElement('input'); 
    newText.type = "text"; 
    //var i = 1; 
    newText.name = "Author[]"; 
    newText.value = counter3 + 2 + ". "; 

    //Counter starts from 2 since we already have one item 
    //newText.class = "input.text"; 
    // Create a new button input 
    var newDelButton = document.createElement('input'); 
    newDelButton.type = "button"; 
    newDelButton.value = "-"; 

    // Append new text input to the newDiv 
    newDiv.appendChild(newText); 
    // Append new button input to the newDiv 
    newDiv.appendChild(newDelButton); 
    // Append newDiv input to the mainContainer div 
    mainContainer.appendChild(newDiv); 
    counter3++; 
    //i++; 

    // Add a handler to button for deleting the newDiv from the mainContainer 
    newDelButton.onclick = function() { 
     mainContainer.removeChild(newDiv); 
     counter3--; 
    } 
} 

這裏是我的PHP代碼:

if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db($database, $con); 



$sql="INSERT INTO savetest (type, number) 
VALUES 
('$_POST[type]','$_POST[Author]')"; 

if (!mysql_query($sql,$con)) 
    { 
    die('Error: ' . mysql_error()); 
    } 
echo "1 record added"; 

mysql_close($con); 
echo "Thank you for submitting your details!"; 

我聽到很多人能得到這個以使用數組的工作,但我存儲在數據庫中的數據是Array 。無論我創建了多少個文本框,只需要Array即可。

我使用正確的方法嗎?我應該將這一組數據保存在一個數據庫字段中嗎?

+0

GeorgioCZY,我已經閱讀了這三次,我仍然無法弄清楚你在問什麼。你是否想要出現另一個文本字段?它沒有出現?另外,你的代碼有幾個格式問題。請修改,幫助會更容易。 – 2012-04-19 22:52:04

+0

如果您想要將所有數據保存到單個字段,則需要implode數據implode(',',$ _POST [Author])。 – 2012-04-20 09:50:13

+0

http://stackoverflow.com/questions/1978438/save-php-array-to-mysql – 2012-04-20 09:55:14

回答

3
if (!$con){ 
    die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db($database, $con); 

$authors = $_POST['Author']; 
foreach($authors as $author) : 
    $sql="INSERT INTO savetest (type, number) VALUES ('{$_POST['type']}','{$author}')"; 

    if (!mysql_query($sql,$con)){ 
     die('Error: ' . mysql_error()); 
    } 
endforeach; 
+0

這工作得很好!非常感謝! – GeorgioCZY 2012-04-20 15:49:34

+0

我可以指出,雖然這回答你的問題,但你不應該把用戶輸入直接放入sql查詢中。請參閱http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php – 2013-05-15 08:20:04

相關問題