简体   繁体   中英

How can I insert appended input field data to mySQL database?

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 ) {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM