0

I append some input fields to my container and want to add for each an entry in my mysql database. This is working well so far:

<?php
if (isset($_POST['submit_val'])) {
    if ($_POST['name']) {
        foreach ( $_POST['name'] as $key=>$value ) {
            $pdo = $db->prepare('INSERT INTO friends (name) values(:name) ');
              $pdo->execute(array(
                ':name' => $value,
              ));
        }
    }
    echo "<i><h2><strong>" . count($_POST['name']) . "</strong> items added</h2></i>";
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
    <form method="post" action="">
        <div id="container">
                <p id="add_field"><a href="#"><span>Click To Add</span></a></p>
        </div>
        <input type="submit" name="submit_val" value="Submit" />
        </form>
<?php } ?>



<script type="text/javascript">
    var counter = 0;
        $(function() {
            $('p#add_field').click(function() {
                counter += 1;
                $('#container').append(
                     '<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><br/>');
            });
       });
</script>

But I wish to have as fields not only name, also age and gender:

$('#container').append('<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><input id="field_' + counter + '" name="age[]' + '" type="text" /><input id="field_' + counter + '" name="gender[]' + '" type="text" /><br/>');

and add them into the database:

 $pdo = $db->prepare('INSERT INTO friends (name,age,gender) values(:name,:age,:gender) ');
    $pdo->execute(array(
         ':name' => $value,
         ':age' => $value,
         ':gender' => $value,
   ));

But now I have a logical problem of understanding. How can I get the other values into my foreach loop foreach ( $_POST['name'] as $key=>$value ) { because I need one loop for all values together?

I could imagine something like this:

foreach ( $_POST['name'] as $key=>$name && $_POST['age'] as $key=>$age && $_POST['gender'] as $key=>$gender ) {

1 Answer 1

1

Assuming occurrences of all the three fields are same you can use:

foreach($_POST['name'] as $key=>$val){
    echo $val." ".$_POST['age'][$key]." ".$_POST['gender'][$key]."<br>";// you can use these value in your insert

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.