我需要从复选框中插入许多值,但是只有最后一个值正在插入数据库中。
HTML代码:
<?php
$conn = mysqli_connect("localhost", "root", "", "fix_in_time");
$result = mysqli_query($conn, "SELECT * FROM `material` WHERE id > 0");
while($row = mysqli_fetch_assoc($result)):?>
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo" id="Tipo"><label><?php echo $row['tipo'];?></label><br>
<?php endwhile;?>
有PHP代码:
$Sala = mysqli_real_escape_string($conn, $_POST['Sala']);
$Descricao = mysqli_real_escape_string($conn, $_POST['Descricao']);
$Tipo = mysqli_real_escape_string($conn, $_POST['Tipo']);
$Data = date("d-m-Y H:i:s", strtotime('-1 hour'));
if(empty($_POST['Sala']) || empty($_POST['Descricao'])||
empty($_POST['Tipo'])){
echo"<script language='javascript' type='text/javascript'>alert('Por favor
preencha os campos!');window.location.href='../index.php';</script>";
exit();
}
if(isset($_POST['submit'])){
if (!empty($_POST['Tipo'])) {
foreach ((array)$Tipo as $Tipo) {
$query = "INSERT INTO `relatorios` (Data, Sala, Descricao, Tipo) VALUES ('$Data', '$Sala', '$Descricao', '$Tipo')";
mysqli_query($conn, $query);
}
}
}
答案 0 :(得分:0)
在您的html代码中,将输入标签更改为:
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo[]">
。
如果您在标签名后附加[]
,则php中的这个post变量将是一个数组。我已删除了标签ID,因为它应该是唯一的,不确定是否需要它,但是如果需要,则使其唯一。
您的php代码应如下所示:
if(isset($_POST['submit'])) {
if (!empty($_POST['Tipo']) && is_array($_POST['Tipo'])) {
foreach ($_POST['Tipo'] as $Tipo) {
$TipoEscaped = mysqli_real_escape_string($conn, $Tipo);
$query = "INSERT INTO `relatorios` (Tipo) VALUES ('$TipoEscaped')";
$success = mysqli_query($conn, $query);
if (!$success) {
//handle mysql error
}
}
}
}