0

I'm trying to insert values from a dynamically-filled input text field. What further steps must I take?

My sample form:

<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>

My insert.php file:

$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); 

}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
ytse_jam
  • 185
  • 2
  • 15
  • 3
    You are using [an obsolete database API](http://stackoverflow.com/q/12859942/19068) and are exposing yourself to [SQL injection attacks](http://bobby-tables.com/) that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 17 '12 at 16:29
  • PDO is a best solution for you @ytse_jam –  Oct 17 '12 at 16:32
  • im just starting to learn php, the question is how can i insert those two arrays(grade and name). since both have the same input name, only the values changes because they are being filled dynamically. – ytse_jam Oct 17 '12 at 16:37

1 Answers1

0

Try it:

Form:

<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); 
}