I have a problem when I want to insert multiple fields into one table.
Here\'s my form:
Add user
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.