我有一个包含340个字段的大型HTML表单,我需要将其输入Microsoft SQL Server 2008 R2。我试图找到一种输入数据的方法,而不必仔细地写出PHP代码中的每个变量(在$ sql& $ params中)。如果列和变量具有相同的名称,也许它是可能的。这是HTML表单和整个PHP coode的较小版本。 SQL表目前只有列"日期" &安培; "部分号码"
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="test" action="http://10.0.0.252/test.php" method="post" accept-charset="ISO-8859-1">
<input type="text" tabindex="1" id="form283_1" value="" data-objref="61 0 R" title="Date:" name="Date" />
<input type="text" tabindex="4" id="form339_1" value="" data-objref="62 0 R" title="PartNo." name="PartNo" />
<input type="submit" value="Submit" id="form366_1">
</form>
</body>
</html>
PHP代码:
<?php
$post = file_get_contents('php://input');
$serverName = "FILESERV1\SQLEXPRESS";
$connectionInfo = array(
"UID" => "user",
"PWD" => "Password",
"Database" => "ipadforms"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) die("<pre>".print_r(sqlsrv_errors(), true));
echo "Successfully connected!";
if(empty($_POST) === false && empty($errors)=== true)
{
$sql = "INSERT INTO dbo.MF001 (Date,PartNumber) VALUES (?,?)";
$params = array($post);
$stmt = sqlsrv_query( $conn, $sql , $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_close($conn);
}
答案 0 :(得分:0)
拥有一系列表单字段名称 - &gt;表字段名称,然后迭代它?
$fields = array('formfield1' => 'dbfield1', 'formfield2' => 'dbfield2', etc...);
foreach($fields as $formfield => $dbfield) {
$sql = "INSERT INTO dbo.FM001 ($dbfield) VALUES (?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST[$formfield));
}
请注意,$dbfield
必须直接插入到查询字符串中,因为占位符只能表示VALUES,而不能表示sql关键字或标识符。