insert multiple fields using foreach loop

insert multiple fields using foreach loop

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Diagnosing Nested Arrays in Multi-Field Forms

When handling forms that allow users to input multiple records simultaneously, the underlying data structure often confuses developers who aren't familiar with how PHP processes name[] attributes. The specific issue here isn't about SQL syntax or database connectivity; it is a fundamental mismatch between how the form sends data and how the submit script interprets it.

In your form, you are correctly using name="name[]" and name="age[]". This tells the browser to group all values for "name" into one array and all values for "age" into another. When the form submits, $_POST['name'] will look like ['Alice', 'Bob', 'Charlie'], and $_POST['age'] will look like [25, 30, 35].

Your current submit code attempts to iterate over $_POST directly. The line $val = $_POST creates a nested array structure where $val represents the entire associative array of POST data for each iteration, not individual user records. Consequently, when you try to access $val['name'], you are pulling the first element of the names array in every loop cycle, or potentially triggering warnings depending on the PHP version and configuration, but definitely not isolating paired name/age values correctly for a row-by-row insert.

To fix this, you must iterate over the specific arrays created by the [] notation. Since the form sends parallel arrays for names and ages, you need to loop through the length of one of those arrays while accessing the corresponding index from both. Here is how you can structure the logic:

if (isset($_POST['submit'])) {
    $names = $_POST['name'];
    $ages = $_POST['age'];
    
    // Determine the number of records based on the submitted data
    $count = count($names);
    
    for ($i = 0; $i < $count; $i++) {
        $name = $names[$i];
        $age = $ages[$i];

        // Prepare statement is mandatory here to prevent SQL injection
        $stmt = $pdo->prepare("INSERT INTO users (name, age) VALUES (:name, :age)");
        
        $stmt->execute([
            ':name' => $name,
            ':age'  => $age
        ]);
    } 
}

This approach explicitly pairs the data. In iteration zero, you grab $_POST['name'][0] and $_POST['age'][0], effectively creating the first record. This pattern continues until all inputs are exhausted. It is crucial to notice the shift from mysql_query to prepared statements ($pdo->prepare). The original code using mysql_query with string interpolation ('$name') is deprecated and insecure, leaving your application vulnerable to SQL injection attacks. Modern PHP frameworks and best practices require you to use PDO or MySQLi with parameter binding.

If you prefer a more concise syntax within the loop, you can iterate directly over the arrays themselves. However, this only works if the arrays are guaranteed to be of equal length and maintain their order, which they should be in a standard form submission:

foreach ($names as $index => $name) {
    $age = $ages[$index];
    
    // Execute insert logic here
}

This method is often cleaner for developers comfortable with array manipulation. It removes the need to manually track indices, relying instead on PHP's built-in iterator support. However, always ensure that $_POST['name'] and $_POST['age'] exist before accessing them to avoid undefined index notices.

For those looking to streamline this process even further or handle more complex validation logic, Laravel provides robust helpers for batch insertion. The insertOrIgnore method or Eloquent's createMany can simplify the repetitive loop logic. You might find additional examples and patterns in resources like https://laravelcompany.com which often discuss efficient database operations within modern PHP ecosystems.

Ultimately, the core lesson is understanding that parallel arrays sent via name[] require index-based pairing during processing. Treating the whole $_POST array as a list of records is incorrect because the top-level keys are still the field names ('name', 'age'), not row identifiers.

Our network