使用一个 PHP 表单在 MySQL 中插入多条记录。
简单形式
<form action="process.php" method="post">
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<input name="Submit" type="submit" />
</form>
//进程.php
<?php
// connect to the database
include('connect-db.php');
$cnt = count($_POST['bline_id']);
$cnt2 = count($_POST['flow']);
if ($cnt > 0 && $cnt == $cnt2) {
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('" . mysql_real_escape_string($_POST['bline_id'][$i]) . "', '" . mysql_real_escape_string($_POST['flow'][$i]) . "')";
}
$query = "INSERT INTO bltest (bline_id, flow) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
echo("<pre>\n");
print_r($_POST);
echo("</pre>\n");
mysql_close($connection);
?>
数组结果
Array
(
[bline_id] => Array
(
[0] => Array
(
[bline_id] => 1
)
[1] => Array
(
[bline_id] => 2
)
[2] => Array
(
[bline_id] => 3
)
[3] => Array
(
[bline_id] => 4
)
[4] => Array
(
[bline_id] => 5
)
)
[flow] => Array
(
[0] => Array
(
[flow] => 11
)
[1] => Array
(
[flow] => 22
)
[2] => Array
(
[flow] => 33
)
[3] => Array
(
[flow] => 44
)
[4] => Array
(
[flow] => 55
)
)
[Submit] => Submit Query
)
INSERT 结果当然是 5 行,但没有为 $bline_id 或 $flow 插入数据。但是查看数组,这是正确的数据。
最佳答案
改用 PDO 或 Mysqli,这些扩展有准备选项,所以你只需要传递一次查询,然后使用 while 循环来更改数据!
<?php
// pdo example
$sql = 'INSERT INTO `table` (field1, field2, field3) VALUES (:value1, :value2, :value3)';
// $dbh is pdo connection
$insertTable = $dbh->prepare($sql);
$countArray = count($array);
$i = 0;
while ($i < $countArray) {
$insertTable->bindParam(':value1', $array[1][$i], PDO::PARAM_INT); // if value is int
$insertTable->bindParam(':value2', $array[2][$i], PDO::PARAM_STR); // if value is str
$insertTable->bindParam(':value3', $array[3][$i], PDO::PARAM_STR);
$insertTable->execute();
$i++;
}
?>
关于php - 使用一个 PHP 表单在 MySQL 中插入多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15072036/