如何使用foreachloop将多个复选框表单插入数据库

时间:2019-05-11 16:22:50

标签: php mysql

在将多个复选框值插入数据库后,我仅得到一个复选框结果。我认为我的foreach循环有问题。

这是我的html复选框表单,我正在尝试使用表单验证方法通过foreach循环插入数据库中...

<div class="custom-control custom-checkbox">
        <input type="checkbox" name="category[]" value="r_land" class="custom-control-input" id="customCheckland_R">
        <label class="custom-control-label" for="customCheckland_R">Land</label>
        </div>
        <div class="custom-control custom-checkbox">
        <input type="checkbox" name="category[]" value="r_duplex" class="custom-control-input" id="customCheckduplexes_R">
        <label class="custom-control-label" for="customCheckduplexes_R">Duplexes</label>
        </div>
        <div class="custom-control custom-checkbox">
        <input type="checkbox" name="category[]" value="r_hotel" class="custom-control-input" id="customCheckhotels_R">
        <label class="custom-control-label" for="customCheckhotels_R">Hotels</label>
        </div>

$category = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());

if($_SERVER["REQUEST_METHOD"] == "POST"){

if(empty($_POST["category"])){
    $category_error  = "<div class=''>Atleast one category is required</div>";
}

if($category_error == ""){
    $category                = $_POST["category"];
    $user                    = new Property_request();

    foreach($category as $cate){
    $user->category          = $cate;   
    }
    $user->created_at        = $timestamp;
    $user->save();
}



if(empty($_POST["message"])){
    $message = "";
}   else{
    $message = test_input($_POST["message"]);
}
}

function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = htmlentities($data);
    return $data;
}
?>

0 个答案:

没有答案