Lewisandclark 200
Lewisandclark 200

Reputation: 41

Having trouble with a foreach + mysql INSERT

I am wondering if it's possible to create a dynamic table that inserts in mysql. What I have is this small table that a user can expand as needed. (To get as many input rows as they wish.)

<script>
var count = 0;
$(function(){
$('p#add_field').click(function(){
    count += 1;
    $('#container').append(
            '<strong>Recipient #' + count + '</strong><br />' 
            + '<tr><td><label>Client First Name:</label><input id="f_name_' + count + '" name="f_name[]' + '" type="text" /></td><td><label>Client Last Name:</label><input id="l_name_' + count + '" name="l_name[]' + '" type="text" /></td></tr>');

});
});
</script>

The JS sets up nice input ids and names (f_name_1, f_name_2, l_name_1, l_name_2, etc.) but the trouble for me starts when I try to iterate through the inputs and insert the values into MYSQL. This works great if you only submit one row (name). Alas, if you want to submit two rows (names) it runs through the loop and inserts four rows into the DB.

i.e.
John Doe
Jane Eyre
John Eyre
Jane Doe

Here is the INSERT:

//Loop through added fields
foreach ( $_POST['f_name'] as $key=>$f_name) {
  foreach ( $_POST['l_name'] as $key=>$l_name) {

    //Insert static values into table
    $sql_user = sprintf("INSERT INTO mytable (f_name, l_name) VALUES ('%s','%s')",
    mysql_real_escape_string($f_name),
    mysql_real_escape_string($l_name));
    $result_user = $db->query($sql_user);   
    }
    }               


<?php if (!isset($_POST['btnSubmit'])) { ?>
<h1>My Form</h1>
    <form name="userdata" method="post" action="">

    <h3>Please list the names:</h3>
<table>
    <div id="container">
        <p id="add_field"><a href="#"><span>+ Add Names</span></a></p>
    </div>
</table>

    <input type="submit" name="btnSubmit" id="go" value="Submit Your Names" class="btn" />


    </form>
<?php } ?>

Thanks for any advice as this is something I've never been able to figure out.

JE

Upvotes: 1

Views: 580

Answers (1)

mellamokb
mellamokb

Reputation: 56769

You are looping through both arrays nested inside each other, so you get every possible combination of both. You want to loop through only one of the arrays, and use the index to lookup the corresponding value in the other array:

foreach ( $_POST['f_name'] as $key => $f_name ) {
    $l_name = $_POST['l_name'][$key];
    // do something with $f_name and $l_name
}

Upvotes: 1

Related Questions