簡體   English   中英

如何從具有多行的HTML表單動態地向數據庫插入多行?

[英]How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?

所以這就是我的情況。 我有一個表單,使用戶能夠向表單添加任意數量的行,並向這些新創建的行中輸入更多數據(使用javascript)。 我已經在以下代碼中進行了設置(我正在使用index.html,js / scripts.js和php / upload.php文件,所有這些文件都是外部鏈接的,包括外部CSS):

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和服務器端腳本能夠使用以下代碼為第一行提交信息:

JAVASCRIPT文件

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行。 請指教!

這里着重討論這個問題的HTML部分,是一種動態增長表單的方法:

首先是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:

$(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;
}

制作這個演示

這是正在發生的事情的分解。 首先, table元素可以定義多個主體,因此,我添加了一個空輸入行的HTML,並將其隱藏(使用CSS)在帶有IDtemplatetbody中。 然后,我使用JavaScript定義了一個簡單函數,該函數只是將該行的內容附加到帶有inputs ID的tbody ,並將該函數綁定到buttonclick事件。 然后,因為輸入tbody為空開始,所以我一次調用了該函數。 然后,為了提交表單,我選擇了inputs tbody所有行,並遍歷了其中的所有inputs 接下來,我將它們組合成一個大的JavaScript對象數組,每個元素代表一行,最后我將其發布,展示了從客戶端到服務器的往返數據(我正在使用JSON2.js進行序列化數據)。 您的PHP頁面將在此處進行拾取以在服務器上進行檢查,然后(使用准備好的語句)將有效行插入數據庫。

您的PHP將采用這樣的POSTed值:

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

並將提交的數據視為關聯數組。 這種方法使用AJAX表單發布,因此PHP頁面的響應應為有效的JSON,其結構如下所示:

{Success: true}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM