简体   繁体   English

如何使用PHP将输入数组表单字段插入数据库表

[英]How to Insert Input Array Form Fields into a Database Table using PHP

I have two php files. 我有两个php文件。 One is to hold the form/table data and have requesters to input form data and the other php file is to process the form data and have it insert the information that is inputted on the main page to a database. 一种是保存表单/表数据,并让请求者输入表单数据,另一种php文件是处理表单数据,并将其插入在主页上输入的信息到数据库中。 I have the connection info right so I left it out for privacy reasons. 我的连接信息正确,因此出于隐私原因,我将其省略。 My question is, how do I or should I submit the information from the form and make the array into a string before submitting it to the target table? 我的问题是,在提交给目标表之前,我应该如何还是应该从表单中提交信息并使数组成为字符串? When I try to insert as is, it returns an error message saying my syntax is wrong but all the session variables are being read because it returns the input fields values. 当我尝试按原样插入时,它返回一条错误消息,指出我的语法错误,但由于它返回输入字段的值,因此正在读取所有会话变量。 Below is a copy of what I have tried thus far. 以下是到目前为止我尝试过的内容的副本。 I'm going to have 10 initial fields with the option to add more rows but, for the sake of length, I shortened the table to two initial rows. 我将拥有10个初始字段,并可以选择添加更多行,但是出于篇幅考虑,我将表缩短为两个初始行。

Here is my main form page: SANTable.php 这是我的主要表单页面:SANTable.php

<?php
session_start();
// If this is the initial trip, set up the $_SESSION.
if (!isset($_SESSION['initial_pass'])){
    $_SESSION['initial_pass']=true;
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SAN Fiber Request</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="wrapper">
<div id="maincontent">

<hr class="GreyHorizon">
<form id="sanFiber" action="insert.php" method="post">
<table class="frame" id="sanRequest" style="display: block;">
    <tr>
        <th style="border:none">&nbsp;</th>
        <th><b class="RedAsterik">*</b>Host Name</th>
        <th><b class="RedAsterik">*</b>Network Type</th>
        <th><b class="RedAsterik">*</b>Description</th>
        <th><b class="RedAsterik">*</b>Server Port Used</th>
        <th><b class="RedAsterik">*</b>Speed</th>
        <th><b class="RedAsterik">*</b>Mgmt Arms/Swings RT or LT</th>
        <th><b class="RedAsterik">*</b>Primary Function</th>
        <th><b class="RedAsterik">*</b>Comments</th>
    </tr>
    <tr>
        <td style="border:none"><img src="images/plus2.png" name="myImage" id="swap1" class="toggler" /></td>
        <!--25-->
        <td><input name="host[]" class="field" type="text" size="15" /></td>
        <!--25-->
        <td><select name="NETTYPEdropdown[]" id="NETTYPEdropdown">
            <option selected="selected" value=""></option>
            <option value="FiberChannel">Fiber Channel</option>
        </select></td>
        <!--50-->
        <td><select name="Descriptiondropdown[]" id="Descriptiondropdown" class="Description_dropdown">
            <option selected="selected" value=""></option>
            <option value="PriA">Primary Fabric A</option>
            <option value="PriB">Primary Fabric B</option>
            <option value="SecA">Secondary Fabric A</option>
            <option value="SecB">Secondary Fabric B</option>
            <option value="BackA">Backup Fabric A</option>
            <option value="BackB">Backup Fabric B</option>
            <option value="ilo-Manage">ilo-Management</option>
            <option value="UTCS265">UTCS Private 265</option>
            <option value="addOther">Other...</option>
        </select></td>
        <!--30-->
        <td><input name="PortUsed[]" class="field" type="text" id="PortUsed" size="15" /></td>
        <!--15-->
        <td><select name="Speeddropdown[]" id="Speeddropdown">
            <option selected="selected" value=""></option>
            <option value="1GB">1GB</option>
            <option value="4GB">4GB</option>
            <option value="8GB">8GB</option>
            <option value="10GB">10GB</option>
            <option value="16GB">16GB</option>
        </select></td>
        <!--15-->
        <td><select name="MGMTdropdown[]" id="MGMTdropdown">
            <option selected="selected" value=""></option>
            <option value="YesR">Yes - Right</option>
            <option value="YesL">Yes - Left</option>
            <option value="No">No</option>
        </select></td>
        <!--50-->
        <td><input name="primary[]" class="field" type="text" id="primary" size="25" /></td>
        <!--250-->
        <td><textarea name="comments[]" class="field" type="text" id="comments" size="20"></textarea></td>
    </tr>
</table>
<br>
<fieldset id="buttons">
    <input class="fsSubmitButton" type="submit" value="Review" /> 
    <input class="fsSaveButton" id="save" type="submit" value="Save" />
    <a href="#bottom" name="bottom"><input class="fsAddButton" type="button" value="Add New Row" /></a>
    <input class="fsNewHostButton" type="submit" value="Add New Host" />
</fieldset> 
</form>
    </div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#save").click(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
cache: false,
success: function(){
    alert('success');
},
error: function(e){
    alert('nope.');
}
});
return false;
});
});
</script>

</body>
</html>

And here's my insert.php: 这是我的insert.php:

<?php 
if (session_id() == '') {
session_start();
}
else {
var_dump(session_id());
}

/*
   ***Connection info***
*/


//for SAN Fiber Request
$_SESSION['host'] = $_POST['host'];
$_SESSION['netType'] = $_POST['NETTYPEdropdown'];
$_SESSION['description'] = $_POST['Descriptiondropdown'];
$_SESSION['used'] =  $_POST['PortUsed'];
$_SESSION['speed'] = $_POST['Speeddropdown'];
$_SESSION['mgmt'] = $_POST['MGMTdropdown'];
$_SESSION['primary'] = $_POST['primary'];
$_SESSION['comments'] = $_POST['comments'];

    $number = count($_SESSION['host']);
    for ($i=0; $i<$number; $i++)
    {
        $hostno = $_SESSION['host'][$i];
        $netTypeno = $_SESSION['netType'][$i];
        $descriptno = $_SESSION['description'][$i];
        $usedno = $_SESSION['used'][$i];
        $speedno = $_SESSION['speed'][$i];
        $mgmtno = $_SESSION['mgmt'][$i];
        $primaryno = $_SESSION['primary'][$i];
        $commentsno = $_SESSION['comments'][$i];

        if ($_SESSION['host'][$i] <> '') { 
            $sql = "INSERT INTO cable_request_san_fiber_detail (CABLE_REQUEST_SAN_FIBER_DETAIL_ID, CABLE_REQUEST_ID, NETWORK_TYPE, HARDWARE_PORT_ID, SERVER_PORT, SPEED,  MANAGEMENT_ARM, PRIMARY_FUNCTION, CABLE_LABEL, SWITCH_HARDWARE_PORT_ID, DESCRIPTION, HARDWARE_ID, COMMENTS) VALUES (, 1, $netTypeno, ,$usedno, $speedno, $mgmtno, $primaryno, $hostno, ,$descriptno, , $commentsno)";

            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
    }

$conn->close();
?>

How should I retrieve the values pulled from the input fields on the html page in the php page to process the insert query? 我应该如何检索从php页的html页的html页的输入字段中提取的值来处理插入查询?

Im no senior guy, but I see two main not clear situations to start in your code: 我不是资深人士,但我发现您的代码中有两个主要的不清楚情况:

1) I dont see how you are able to send to the insert.php more than one form at a time or how you want to set multiple sessions simultaniously... So that line 1)我看不到您如何一次可以将多个表单发送到insert.php,或者您如何同时设置多个会话...

$number = count($_SESSION['host']); $ number = count($ _ SESSION ['host']);

...with the for loop is unecessary. ...使用for循环是不必要的。 If you dont need those sessions, I would set the post stuff right into the variables to start testing... 如果您不需要这些会话,我将把帖子内容直接设置到变量中以开始测试...

2) That apparently is not the way to send data through a Jquery.ajax. 2)显然,这不是通过Jquery.ajax发送数据的方法。 You have to .serialize the form and when you receive it in the insert.php, you convert to something you can use. 您必须.serialize表格,当您在insert.php中收到表格时,您将转换为可以使用的表格。 Try this documentation to see it better: 请尝试以下文档以更好地查看它:

https://api.jquery.com/serialize/ http://api.jquery.com/jquery.ajax/ https://api.jquery.com/serialize/ http://api.jquery.com/jquery.ajax/

hope that works :) 希望有效:)

After a bit of trial and error and looking at my code closely, I made it work by changing the write up of my query. 经过一番尝试和错误并仔细查看了我的代码,我通过更改查询的内容使其工作。 After I added a value of default for the auto-increment field and properly organized my quotes for referencing the string variables, everything worked just fine. 在为auto-increment字段添加default值并正确组织了引号来引用字符串变量后,一切正常。 Single and double quote usage can be quite tricky. 单引号和双引号用法可能非常棘手。 Here's my solution: 这是我的解决方案:

$sql = "INSERT INTO cable_request_san_fiber_detail(CABLE_REQUEST_SAN_FIBER_DETAIL_ID,
CABLE_REQUEST_ID, NETWORK_TYPE, HARDWARE_PORT_ID, SERVER_PORT, SPEED,  MANAGEMENT_ARM, 
PRIMARY_FUNCTION, CABLE_LABEL, SWITCH_HARDWARE_PORT_ID, DESCRIPTION, HARDWARE_ID, 
COMMENTS) VALUES (default, 1, '".$netTypeno."','','".$usedno."','".$speedno."',
 '".$mgmtno."', '".$primaryno."', '".$hostno."','',
'".$descriptno."','','".$commentsno."')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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