首先,PHP 不能很好地处理具有相同名称的 GET/POST 变量,每个变量都会覆盖前一个变量,因此您需要类似以下内容:
<label>Volunteer: <input type="text" name="volunteer_id[0]" size="7" /></label>
<label>Position: <input type="text" name="position_id[0]" size="7" /></label>
<label>Memo: <textarea name="memo[0]" cols="45" rows="2"></textarea></label>
这些应该按收到的顺序编入索引,但为了安全起见,在生成 HTML 的代码中,您应该将索引添加到名称中(例如 volunteer_id[0]) - 空的 <textarea> 数据不会得到已发布,因此您需要确保它存在正确的索引,否则您最终可能会收到与志愿者/职位不相符的备忘录。
你可以循环一个函数来创建你的输出;当 PHP 收到时,这将在$_POST 中为您提供 3 个数组(我假设您的表单方法是“post”),如下所示:
//these will all be arrays
$aVolunteers = $_POST['volunteer_id'];
$aPositions = $_POST['position_id'];
$aMemos = $_POST['memo'];
接下来,构建查询:
//how many volunteers are there
// - text input fields are always posted even when empty
// so counting volunteers should tell us how many data sets we've got
$iNumSets = count($aVolunteers);
//begin the query
$sQuery = "INSERT INTO work(volunteer_id, position_id, memo) VALUES";
//create an array of parameters to bind
$aBoundParams = array();
//loop to the total number of data sets
for($i = 0; $i < $iNumSets; $i++) {
//append the "values" to the query string
$sQuery .= "(?, ?, ?), ";
//add the values to the bound parameters array
// assumes the database fields are NULLable
$aBoundParams[] = !empty($aVolunteers[$i]) ? $aVolunteers[$i] : null;
$aBoundParams[] = !empty($aPositions[$i]) ? $aPositions[$i] : null;
//this one is the most important one to check !empty()
//as it's possible $aMemos[$i] doesn't exist
$aBoundParams[] = !empty($aMemos[$i]) ? $aMemos[$i] : null;
}
//trim the trailing ", "
$sQuery = substr($sQuery, 0, -2);
如果您的数据集发布了 3 次,您现在应该有如下查询:
INSERT INTO work(volunteer_id, position_id, memo) VALUES(?, ?, ?), (?, ?, ?), (?, ?, ?)
还有一个长度为 9 的数组,如下所示:
array(
$aVolunteers[0],
$aPositions[0],
$aMemos[0],
$aVolunteers[1],
$aPositions[1],
$aMemos[1],
$aVolunteers[2],
$aPositions[2],
$aMemos[2]
)
您现在应该能够准备查询、绑定参数/值并执行它。
//prepare the statement
$oStmt = $dbo->prepare($sQuery);
//bind the parameters to the statement
// parameters need to be bound by reference - note &$vParamValue
foreach($aBoundParams as $iParamIndex => &$vParamValue) {
$oStmt->bindParam(
//bound params/values are 1 indexed rather than 0
($iParamIndex + 1),
//value to bind
$vParamValue,
//basic variable type prep - assuming you're using PDO
(is_int($vParamValue) ? PDO::PARAM_INT : PDO::PARAM_STR)
);
}
//execute the statement
$oStmt->execute();