我正在尝试以相同的形式创建多个HTML插入,因此我可以快速在我的数据库中插入多行以节省时间。但是我不确定如何处理这个问题。
<form action="admin1.php" method="post">
<?php
function multiform($x){
for ($x = 0; $x < 3; $x++){
echo 'Episode: <input type="number" name="Episode[]">
Date: <input type="date" name="Date[]">
Guest: <input type="text" name="Guest[]">
Type: <input type="text" name="Type[]">
Youtube:<input type="text" name="Youtube[]"> MP3: <input type="text" name="MP3[]"> iTunes:<input type="text" name="Itunes[]"><br/><br/>';
}
}
multiform(0);
?>
<input type="submit" value="Submit Form" name="submitForm">
</form>
这是我试图使用的:
$con = mysqli_connect("server","root","","database");
function multiformpost($x) {
for ($x = 0; $x < 3; $x++) {
$Episode = $_POST['Episode'][$x];
$Date = $_POST['Date'][$x];
$Guest = $_POST['Guest'][$x];
$Type = $_POST['Type'][$x];
$Youtube = $_POST['Youtube'][$x];
$MP3 = $_POST['MP3'][$x];
$Itunes = $_POST['Itunes'][$x];
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}')";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
if (!mysqli_query($con, $sql)) {
die ('Error: ' . mysqli_error($con));
}
echo "Added to database";
}
}
multiformpost(0);
mysqli_close($con);
只是返回一个空白屏幕..我知道这是错的,但我不完全确定原因。
答案 0 :(得分:1)
您需要在循环中构建SQL的VALUES
部分,然后执行单个查询。所以像这样:
$con = mysqli_connect("","","","");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
multiformpost($con);
mysqli_close($con);
function multiformpost($db) {
if(empty($db) {
throw new Exception('You need to pass a valid mysqli connection to this method');
}
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ";
$size = count($_POST['Episode']);
for ($x = 0; $x < $size; $x++) {
$Episode = mysqli_real_escape_string($db,$_POST['Episode'][$x]);
$Date = mysqli_real_escape_string($db,$_POST['Date'][$x]);
$Guest = mysqli_real_escape_string($db,$_POST['Guest'][$x]);
$Type = mysqli_real_escape_string($db,$_POST['Type'][$x]);
$Youtube = mysqli_real_escape_string($db,$_POST['Youtube'][$x]);
$MP3 = mysqli_real_escape_string($db,$_POST['MP3'][$x]);
$Itunes = mysqli_real_escape_string($db,$_POST['Itunes'][$x]);
$sql .= "('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}'),";
}
$sql = rtrim($sql,',');
if (!mysqli_query($db, $sql)) {
die ('Error: ' . mysqli_error($db));
}
echo "Added to database";
}
请注意,我也做了以下更改,我也建议:
$con
(对于全局范围)和$db
(对于函数中的局部sope)的使用,以便您不会混淆这两者。以前,您的代码在函数范围内引用$con
而未声明global
,因此该变量甚至不可用。强烈建议使用此依赖注入方法,而不是使用global
。