insert multiple fields using foreach loop

foreach, mysql, php

Solution

You are doing a foreach on `$_POST` rather than on the name/age arrays. You should be doing foreach on name or age array like this:

if (
   !empty($_POST['name']) && !empty($_POST['age']) &&
   is_array($_POST['name']) && is_array($_POST['age']) &&
   count($_POST['name']) === count($_POST['age'])
) {
    $name_array = $_POST['name'];
    $age_array = $_POST['age'];
    for ($i = 0; $i < count($name_array); $i++) {

        $name = mysql_real_escape_string($name_array[$i]);
        $age = mysql_real_escape_string($age_array[$i]);

        mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
    } 
}

I would also note that you are currently susceptible to SQL injection so I added the step of escaping your strings for name/age.

I would also highly suggest simply making a single bulk insert into the DB instead of an insert of each record individually (I will leave that up to you to implement). This approach is almost always preferable from a performance standpoint.

Finally, you REALLY should not be using `mysql_*` functions as they are deprecated. Consider changing to mysqli or PDO.

Problem

I have a problem when I want to insert multiple fields into one table. Here's my form: ``` <h1>Add user</h1> <form method="post" action="index.php"> <table> <thead> <th>Name</th> <th>Age</th> </thead> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr> <tr> <td><input name="name[]" type="text" /></td> <td><input name="age[]" type="text" /></td> </tr> </table> <input type="submit" name="submit" value="Submit" /> </form> ``` And here's the submit code: ``` if (isset($_POST['submit'])) { foreach ($_POST as $val) { $name = $val['name']; $age = $val['age']; mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')"); } } ``` The query inserts into the database, but not the values that I've entered. Can someone please help me?

Original source