【问题标题】:Add dynamic inputs and insert data to MySQL添加动态输入并将数据插入 MySQL
【发布时间】:2015-05-05 13:24:44
【问题描述】:

我有一个包含输入的表单,并且有一个按钮可以在下面添加同一行,以便在需要时插入更多数据。目前我没有尝试将它插入到我的数据库中,我只想在一个名为“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>

这是 f.php 代码:

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

请您帮我解决这个问题,并告诉我我在这里做错了什么。

非常感谢。

【问题讨论】:

  • 尝试在 f.php 中使用 print_r($_POST)。
  • 试过但仍然得到一个数组: Array ( [hours1] => Array ( [0] => 12 ) [hours2] => Array ( [0] => 15 ) [durationh] = > Array ( [0] => 3 ) [hrscode] => Array ( [0] => 6 ) [remark] => some text here ) 而没有得到第二行或第三行
  • 请拆分您要附加到包装器的 html 代码。读起来很可怕。它是 jquery 最大的特点之一。 $('&lt;div&gt;') 创建一个 div-元素(适用于所有元素),使用 .attr("attribute", "value") 您可以添加属性。请使用这些功能,以便我们更好地帮助您。

标签: php jquery mysql dynamic


【解决方案1】:

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

【讨论】:

  • 我的问题是我在哪里添加新行(与那里的表格相同)并且我无法获取这些数据。请查看我的 jquery 部分,它在第一行下添加了相同的 hours1[]
  • 1. wrapper 已经是一个 jquery 元素,所以将 $(wrapper) 替换为 wrapper。 2. 当你重构它时,我会查看你附加的 html 代码 ($(wrapper).append(/* html code */))。只要格式不正确,我就无法/不会阅读它。详细说明请看我上面的评论。
【解决方案2】:

创建数据库

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`) );

在 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>

将这些代码添加到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();

并将这些代码添加到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 );
}

【讨论】:

  • 您的解决方案非常不安全。您应该使用准备好的语句来防止 sql 注入。
  • $count = count($_POST['hours1']);回声$计数;当我从最后一页发布两个小时 1 时,它给了我 1。
  • 我已经编辑了我的答案并添加了用于创建数据库和表的数据库查询
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2015-06-21
  • 2016-03-23
相关资源
最近更新 更多