如何动态地从多行中的HTML表单中将多行插入数据库? [英] How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?

查看:75
本文介绍了如何动态地从多行中的HTML表单中将多行插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的情况。我有一个表单,使用户能够向表单添加任意数量的行,并将更多的数据输入到新创建的行(使用javascript)。我已经在以下代码中设置了这个(我使用的是index.html,js / scripts.js和一个php / upload.php文件,都是外部链接的,包括外部CSS):

so here's my situation. I have a form that gives the user the ability to add any number of rows to the form and input more data into those newly created rows (using javascript). I HAVE THIS ALREADY set up in the following code (I am using index.html, js/scripts.js and a php/upload.php files, all are externally linked, including an external CSS):

INDEX.HTML

INDEX.HTML

<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
 <script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">   
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
 <title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>

<input type="hidden" id="co_city">
<input type="hidden" id="co_state">
<input type="hidden" id="co_zipcode">

<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
    <td><select id="company_name"></select></td>
    <td><input id="co_name" type="text"></td>
    <td><input type="submit" value="Get GPS" onclick="gpslookup()"></td>
    <td><input id="co_lat" type="text"></td>
    <td><input id="co_long" type="text"></td>
    <td><input id="co_address" type="text"></td>
</tr>
</table>
<table id="tabledata">
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
<!--Begin Rows-->
<tr>
    <td><input type="checkbox"></td>
    <td><input id="border_location" type="text" name="txt[]"></td>
    <td><input id="cable_location" type="text" name="txt[]"></td>
    <td><input id="vault_direction" type="text" name="txt[]"></td>
    <td><input id="cable_type" type="text" name="txt[]"></td>
    <td><input id="cable_size" type="text" name="txt[]"></td>
    <td><input id="cable_gauge" type="text" name="txt[]"></td>
    <td><input id="vertical" type="text" name="txt[]"></td>
    <td><input id="jumpers" type="text" name="txt[]"></td>
    <td><input id="protectors" type="text" name="txt[]"></td>
    <td><input id="metered_dist" type="text" name="txt[]"></td>
    <td><input id="comments" type="text" name="txt[]"></td>
</tr>
</table>
<input id="addrow_btn" type="submit" value="Add New Row" onclick="addRow(); return false;" />
<input id="delrow_btn" type="submit" value="Delete Row" onclick="deleteRow(); return false;" />
<input id="submit" type="submit" value="Submit" onclick="uploaddata(); return false;"  />
</body>
</html>

至于后端,我只能让PHP和服务器端脚本能够首先提交信息使用以下代码的行:

As for the backend, I ONLY have the PHP and server side scripts able to submit information for that first row using the below code:

JAVASCRIPT FILE

JAVASCRIPT FILE

function addRow() {

var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var colCount = table.rows[1].cells.length;

for(var i=0; i<colCount; i++) {

    var newcell = row.insertCell(i);

    newcell.innerHTML = table.rows[1].cells[i].innerHTML;
    //alert(newcell.childNodes);
    switch(newcell.childNodes[0].type) {
        case "text":
                newcell.childNodes[0].value = "";
                break;
        case "checkbox":
                newcell.childNodes[0].checked = false;
                break;
    }
}
//UPLOAD DATA
//Global variables
var survey = {
    'co_name' : "",
    'co_lat' : "",
    'co_long' : "",
    'co_address' : "",
    'border_location' : "",
    'cable_location' : "",
    'vault_direction' : "",
    'cable_type' : "",
    'cable_size' : "",
    'cable_gauge' : "",
    'vertical' : "",
    'jumpers' : "",
    'protectors' : "",
    'metered_dist' : "",
    'comments' : "",
    'company_name' : "",
    'co_city' : "",
    'co_state' : "",
    'co_zipcode' : ""
    }

function uploaddata() { 

//Read all of the data from the page
for (eID in survey) {
    survey[eID] = document.getElementById(eID).value;
}   
 //Insert data into database

            $.ajax({
            type: 'POST',
            url: './php/upload_survey.php',
            data: survey,
            async: false,
            dataType: 'text',
            success: function() {
            alert("Thank you. Your survey has been submitted.");
            window.location.reload();
            },

                error: function(jqXHR, textStatus, errorThrown) {
                    alert("Error... " + textStatus + "\n" + errorThrown);
                }
        });
    }

PHP文件

//Assign passed parameters

    $co_name = $_POST['co_name'];
    $co_lat = $_POST['co_lat'];
    $co_long = $_POST['co_long'];
    $co_address = $_POST['co_address'];     
    $border_location = $_POST['border_location'];
    $cable_location = $_POST['cable_location'];
    $vault_direction = $_POST['vault_direction'];
    $cable_type = $_POST['cable_type'];
    $cable_size = $_POST['cable_size'];
    $cable_gauge = $_POST['cable_gauge'];
    $vertical = $_POST['vertical'];
    $jumpers = $_POST['jumpers'];
    $protectors = $_POST['protectors'];
    $metered_dist = $_POST['metered_dist'];
    $comments = $_POST['comments'];
    $txt = $_POST['txt'];

    $stringLogInfo =  "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
    log_audit($logAuditFile, $logModule, $stringLogInfo);

//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);



//Insert Survey Form Information into the database
    $fieldlist=$vallist='';
    foreach ($_POST as $key => $value) {
        $fieldlist.=$key.',';
        $vallist.='\''.$value.'\','; 
    }
    $fieldlist=substr($fieldlist, 0, -1);
    $vallist=substr($vallist, 0, -1);
    $sql='INSERT INTO table_name ('.$fieldlist.') VALUES ('.$vallist.')';

mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());

到目前为止,我已经完成其他所有准备就绪的目标是能够循环通过表单中的所有数据,根据他们创建的许多行并将所有这些新行值提交到SQL数据库中的SEPARATE行。请建议!

My objective up to this point, having already everything else sort of ready, is to be able to loop through all the data in the form, according to however many rows they create and submit all those new row values into the SQL Database into SEPARATE rows. Please Advise!

推荐答案

这里关注这个问题的HTML部分是一种动态增长表单的方法:

Focusing on the HTML part of this question here is an approach to grow a form dynamically:

首先是HTML:

<table id="tabledata">
    <thead>
        <th>Select</th>
        <th>Border Location Name</th>
        <th>Cable Location</th>
        <th>Direction of Vault Wall</th>
        <th>Cable Type</th>
        <th>Cable Size (pairs)</th>
        <th>Cable Gauge</th>
        <th>Vertical(s) appeared on Verticals</th>
        <th>Approximate Number of Jumpers</th>
        <th>Are Protectors Still In?</th>
        <th>Metered Distance</th>
        <th class="comments">Central Office Comments</th>
    </thead>
    <tbody id="input"></tbody>
    <tbody id="template">
        <tr>
            <td><input name="selected" type="checkbox" /></td>
            <td><input name="border_location" type="text" /></td>
            <td><input name="cable_location" type="text" /></td>
            <td><input name="vault_direction" type="text" /></td>
            <td><input name="cable_type" type="text" /></td>
            <td><input name="cable_size" type="text" /></td>
            <td><input name="cable_gauge" type="text" /></td>
            <td><input name="vertical" type="text" /></td>
            <td><input name="jumpers" type="text" /></td>
            <td><input name="protectors" type="text" /></td>
            <td><input name="metered_dist" type="text" /></td>
            <td><input name="comments" type="text" /></td>
        </tr>
    </tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button id="ActionSubmit">Submit</button>

此JavaScript:

And This JavaScript:

$(function () {
    var addInputRow = function () {
        $('#input').append($('#template').html());
    };

    addInputRow();
    $('#ActionAddRow').on('click', addInputRow);
    $('#ActionSubmit').on('click', function () {
        var data = $('#input tr').map(function () {
            var values = {};
            $('input', $(this)).each(function () {
                if (this.type === 'checkbox') {
                    values[this.name] = this.checked;
                } else {
                    values[this.name] = this.value;
                }
            });
            return values;
        }).get();
        $.post('/echo/json/', {
            json: JSON.stringify(data),
            delay: 1
        }).done(function (response) {
            alert("POST success");
            console.log(response);
        });
    });
});

然后这个CSS:

tbody#template {
    display: none;
}

生成此演示

以下是对所发生情况的细分。首先元素可以定义多个实体,所以我在中添加了一行空输入和隐藏(用CSS)的HTML使用模板 ID 的tbody 。然后使用JavaScript,我定义了一个简单的函数,只需将该行的内容附加到 tbody ,其ID为 inputs 然后我将该函数绑定到按钮按钮的事件。然后因为输入 tbody 开始为空,我调用该函数一次。然后,为了提交表单,我选择输入的所有行 tbody 并迭代输入在其中找到。接下来,我将它们组合成一个大型JavaScript对象数组,每个元素代表一行,最后我发布这个显示从客户端到服务器的数据往返(我使用JSON2.js来序列化)数据)。您的PHP页面将从此处获取以在服务器上检查它们,并且(使用预准备语句)将有效行插入数据库。

Here is a breakdown of what is happening. First the table element can define mutiple bodies, so I've added the HTML of an empty row of inputs and hidden (with CSS) it in a tbody with the ID of template. Using JavaScript, I then define a simple function that just appends the contents of that row to the tbody with the ID of inputs and I bind that function to the click event of a button. Then because the inputs tbody is starts out as empty I call that function once. Then for submitting the form, I select all rows of the inputs tbody and iterate over the inputs found inside them. Next, I am combining them into one large array of JavaScript objects with each element representing a row, and finally I'm posting this showing a round trip with this data from the client to the server (I'm using JSON2.js to serialize the data). Your PHP page would pick up from here to check them on the server, and (using a prepared statement) insert valid rows into the database.

您的PHP将接受POST像这样的值:

Your PHP would take the POSTed values like this:

$value = json_decode($_POST['json']);

并将提交的数据视为关联数组。这种方法使用AJAX Form Post,因此PHP页面的响应应该是一个有效的JSON,结构如下:

And treat the submitted data as an associative array. This approach uses an AJAX Form Post, so the response of the PHP page should be a valid JSON with a structure something like this:

{Success: true}

这篇关于如何动态地从多行中的HTML表单中将多行插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆