添加动态输入并将数据插入MySQL

时间:2021-07-24 13:17:15

I have a form which has inputs and there is a button that adds the same row underneath to insert more data if its needed. At the moment I'm not trying to insert it to my database, I just want to echo those data in a page called "f.php" but I only see the first row and I'm not be able to see the second+ rows.

我有一个有输入的表单,并且有一个按钮,在下面添加相同的行,以便在需要时插入更多数据。目前我并没有尝试将其插入我的数据库,我只是想在一个名为“f.php”的页面中回显这些数据,但我只看到第一行,我无法看到第二行+ 。

<form action="forms/f.php" method="post" enctype="multipart/form-data"> 
    <tr style="height:85px; text-align:center;">
        <td><input type="text" name="hours1[]" id="hours1" /></td>
        <td><input type="text" name="hours2[]" id="hours2" /></td>
        <td><input type="text" name="durationh[]" id="durationh" /></td>
        <td><input type="text" name="hrscode[]" id="hrscode" /></td>
        <td><textarea name="remark" id="remark[]"></textarea></td>

    </tr> 
</table>
<div class="input_fields_wrap">
</div>
<script>
$(document).ready(function() {
var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<div style="height:80px;"><a href="#" class="remove_field"><img src="img/remove.png"></a><table id="dataTable" width="900" style="margin-left:25px;"><tr style="text-align:center;"><td width="70"><input type="text" name="hours1[]" id="hours1" /></td><td width="64"><input type="text" name="hours2[]" id="hours2" /></td><td width="92"><input type="text" name="durationh[]" id="durationh" /></td><td><input type="text" name="hrscode[]" id="hrscode" /></td><td><textarea name="remark" id="remark[]"></textarea></td></tr></table></div>');
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); x--;
})});
</script><br />    <input type="submit" value="submit">
</form>

This is f.php code:

这是f.php代码:

<?php
$hours = $_POST['hours1'];
$hours1 = $hours[0];
$hours2 = $hours[1];
echo $hours1; echo $hours2;
?>

Could you please help me with a solution to do this and tel me what I'm doing wrong here.

你能帮我解决这个问题吗?请告诉我这里我做错了什么。

Many Thanks.

2 个解决方案

#1


Change the name of the created input fields to hours[] instead of hours1[] and hours2[]. Then you should be able to iterate through all fields.

将创建的输入字段的名称更改为hours []而不是hours1 []和hours2 []。然后你应该能够遍历所有领域。

#2


Create a database

创建一个数据库

CREATE DATABASE `phpstorm`; 
USE `phpstorm`;
CREATE TABLE `phpstorm`.`country_table`( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255), `numcode` VARCHAR(255), `phonecode` VARCHAR(255), `iso3` VARCHAR(255), PRIMARY KEY (`id`) );

add these code in index.php

在index.php中添加这些代码

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
    $(document).ready(function(){
        $(".addmore").on('click', function () {
            var count = $('table tr').length;
            var data = "<tr class='case'><td><span id='snum" + count + "'>" + count + ".</span></td>";
            data += "<td><input class='form-control' type='text' id='c1' name='c1[]'/></td> <td><input class='form-control' type='text' id='c2' name='c2[]'/></td><td><input class='form-control' type='text' id='c3' name='c3[]'/></td><td><input class='form-control' type='text' id='c4' name='c4[]'/></td></tr>";
            $('#form_table').append(data);
            i++;
        });
        $(".delete").on('click', function () {
            $('tr.case:last').remove();
        });
        //insert into database
        $('.insert').on('click', function(){
            $.ajax({
                url: 'ajax.php',
                method: 'post',
                data: $('form#students').serialize(),
                success: function(data){
                    $('#record_list').html(data);
                }
            });
        });
    });
</script>
<form id='students' method='post' name='students' action='index.php'>
    <div class="table-responsive">
        <table id="form_table" class="table table-bordered">
            <tr>
                <th>S. No</th>
                <th>Country Name</th>
                <th>Country Number</th>
                <th>Country Phone code</th>
                <th>Country code</th>
            </tr>
            <tr class='case'>
                <td><span id='snum'>1.</span></td>
                <td><input class="form-control" type='text' id='c1' name='c1[]'/></td>
                <td><input class="form-control" type='text' id='c2' name='c2[]'/></td>
                <td><input class="form-control" type='text' id='c3' name='c3[]'/></td>
                <td><input class="form-control" type='text' id='c4' name='c4[]'/></td>
            </tr>
        </table>
        <input type="hidden" name="is_submit" value="yes"/>
        <button type="button" class='btn btn-danger delete'>- Delete</button>
        <button type="button" class='btn btn-primary insert'>- Insert</button>
        <button type="button" class='btn btn-success addmore'>+ Add More</button>
    </div>
</form>

add these code in config.php

在config.php中添加这些代码

    <?php
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'phpstorm');
    define('DB_USERNAME','root');
    define('DB_PASSWORD','');


$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

and add these code in ajax.php

并在ajax.php中添加这些代码

<?php
require_once 'config.php';
/*Insert values into database*/
if($_POST['is_submit'] == 'yes'){
$count = count($_POST['c1']);
$query_values = array();
for($i=0; $i<$count; $i++){
$c1 = mysql_real_escape_string($_POST['c1'][$i]);
$c2 = mysql_real_escape_string($_POST['c2'][$i]);
$c3 = mysql_real_escape_string($_POST['c3'][$i]);
$c4 = mysql_real_escape_string($_POST['c4'][$i]);

$query_values[] = " ('$c1','$c2','$c3','$c4') ";
}
$values = implode(',', $query_values);
$sql = "INSERT INTO country_table (name, numcode, phonecode, iso3 ) VALUES $values";
mysqli_query( $con, $sql );
}

#1


Change the name of the created input fields to hours[] instead of hours1[] and hours2[]. Then you should be able to iterate through all fields.

将创建的输入字段的名称更改为hours []而不是hours1 []和hours2 []。然后你应该能够遍历所有领域。

#2


Create a database

创建一个数据库

CREATE DATABASE `phpstorm`; 
USE `phpstorm`;
CREATE TABLE `phpstorm`.`country_table`( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255), `numcode` VARCHAR(255), `phonecode` VARCHAR(255), `iso3` VARCHAR(255), PRIMARY KEY (`id`) );

add these code in index.php

在index.php中添加这些代码

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
    $(document).ready(function(){
        $(".addmore").on('click', function () {
            var count = $('table tr').length;
            var data = "<tr class='case'><td><span id='snum" + count + "'>" + count + ".</span></td>";
            data += "<td><input class='form-control' type='text' id='c1' name='c1[]'/></td> <td><input class='form-control' type='text' id='c2' name='c2[]'/></td><td><input class='form-control' type='text' id='c3' name='c3[]'/></td><td><input class='form-control' type='text' id='c4' name='c4[]'/></td></tr>";
            $('#form_table').append(data);
            i++;
        });
        $(".delete").on('click', function () {
            $('tr.case:last').remove();
        });
        //insert into database
        $('.insert').on('click', function(){
            $.ajax({
                url: 'ajax.php',
                method: 'post',
                data: $('form#students').serialize(),
                success: function(data){
                    $('#record_list').html(data);
                }
            });
        });
    });
</script>
<form id='students' method='post' name='students' action='index.php'>
    <div class="table-responsive">
        <table id="form_table" class="table table-bordered">
            <tr>
                <th>S. No</th>
                <th>Country Name</th>
                <th>Country Number</th>
                <th>Country Phone code</th>
                <th>Country code</th>
            </tr>
            <tr class='case'>
                <td><span id='snum'>1.</span></td>
                <td><input class="form-control" type='text' id='c1' name='c1[]'/></td>
                <td><input class="form-control" type='text' id='c2' name='c2[]'/></td>
                <td><input class="form-control" type='text' id='c3' name='c3[]'/></td>
                <td><input class="form-control" type='text' id='c4' name='c4[]'/></td>
            </tr>
        </table>
        <input type="hidden" name="is_submit" value="yes"/>
        <button type="button" class='btn btn-danger delete'>- Delete</button>
        <button type="button" class='btn btn-primary insert'>- Insert</button>
        <button type="button" class='btn btn-success addmore'>+ Add More</button>
    </div>
</form>

add these code in config.php

在config.php中添加这些代码

    <?php
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'phpstorm');
    define('DB_USERNAME','root');
    define('DB_PASSWORD','');


$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();

and add these code in ajax.php

并在ajax.php中添加这些代码

<?php
require_once 'config.php';
/*Insert values into database*/
if($_POST['is_submit'] == 'yes'){
$count = count($_POST['c1']);
$query_values = array();
for($i=0; $i<$count; $i++){
$c1 = mysql_real_escape_string($_POST['c1'][$i]);
$c2 = mysql_real_escape_string($_POST['c2'][$i]);
$c3 = mysql_real_escape_string($_POST['c3'][$i]);
$c4 = mysql_real_escape_string($_POST['c4'][$i]);

$query_values[] = " ('$c1','$c2','$c3','$c4') ";
}
$values = implode(',', $query_values);
$sql = "INSERT INTO country_table (name, numcode, phonecode, iso3 ) VALUES $values";
mysqli_query( $con, $sql );
}