PHP数组输入到数据库的名称

时间:2017-09-17 03:57:35

标签: php arrays

我正在开设酒店专题页面。

我坚持使用的代码如下:

<?php 
$result = mysqli_query($conn, "select * from facilities_type");
while($row = mysqli_fetch_assoc($result))
{
?>
 <tr>
    <th scope="row">
        <input class="form-check-input" type="checkbox" id="blankCheckbox" name="room_feature_cb[]" value="<?php echo $row["facilitiestype_id"]; ?>">
    </th>
    <td>
        <?php echo $row["room_facilities"] ?>
    </td>
    <td>
        <img src="upload-img/icon/<?php echo $row["facilities_icon"]; ?>" width="25">
    </td>
 </tr>
<?php
}
?>

我想使用数组保存数据,但我无法将名称保存到数据库中

if (isset($_POST["room_feature_savebtn"])) 
{
    $feature = $_POST['room_feature_cb'];
    for($result=0;$result>$feature;$result++)
    {
    mysqli_query($conn,"insert into facilities_details(facilitiestype_id) value ('$feature')");
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用foreach,在这种情况下是更好的选择:

if (isset($_POST["room_feature_savebtn"])) 
{
    $features = $_POST['room_feature_cb'];
    foreach ($features as $feature) {
        mysqli_query($conn, "insert into facilities_details(facilitiestype_id) value ('$feature')");
    }
}

你的错误是当你for使用你在这里创建的数组索引($result)时,尝试使用:

if (isset($_POST["room_feature_savebtn"])) 
{
    $feature = $_POST['room_feature_cb'];
    for($result=0; $result < $feature; $result++)   {
        mysqli_query(
            $conn,
            "insert into facilities_details(facilitiestype_id) value ('" . $feature[$result] . "')"
        );
    }

}

我推荐foreach