2012-10-17 111 views
0

我試圖從動態填充的輸入文本字段插入值。我必須採取哪些進一步措施?使用php插入多個數組

我的樣表:

<form action="" method="POST"> 
    <label>Name:</label><input type="text" name="name[]"> 
    <label>Name:</label><input type="text" name="grade[]"> 
    <input type="submit" name="submit"> 
</form> 

我insert.php文件:

$grade = $_POST['grade']; 
$name = $_POST['name']; 
$count_name = count($_POST['name']); 

for($i=0;$i<$count_name ;$i++){ 
    $new_name = $name[$i]; 

    $query = "INSERT INTO test_table (name, grade)VALUES('$new_name','$grade')"; 
    $result = mysql_query($query); 

} 
+2

問題是什麼? –

+3

您正在使用[過時的數據庫API](http://stackoverflow.com/q/12859942/19068),並且正在將自己暴露給[SQL注入攻擊](http://bobby-tables.com/) API會讓你更容易[防守](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)。 – Quentin

+0

PDO是你的最佳解決方案@ytse_jam – 2012-10-17 16:32:47

回答

0

試試:

形式:

<form action="insert.php" method="POST"> 
    <label>Name:</label><input type="text" name="name[]"> 
    <label>Name:</label><input type="text" name="grade[]"> 
    <input type="submit" name="submit"> 
</form> 

insert.php

$grade = $_POST['grade']; 
$name = $_POST['name']; 
$count_name = count($_POST['name']); 

for($i=0;$i<$count_name ;$i++){ 
    $_name = mysql_escape_string($name[$i]); 
    $_grade = mysql_escape_string($grade[$i]); 

    $query = "INSERT INTO test_table (name, grade) VALUES ('$_name','$_grade')"; 
    $result = mysql_query($query); 
}