如何将复选框中的数据插入数据库

时间:2019-01-08 10:21:45

标签: html sql arrays go checkbox

请帮助我,如何从checbox (数组)获取数据,并将其放入数据库, 我只得到这个,但没有发布到数据库中:

enter image description here

这是我的main.go:

func Insert(w http.ResponseWriter, r *http.Request) {
db := dbConn()
if r.Method == "POST" {
    r.ParseForm()
    item_code := r.FormValue("item_code")
    item_name := r.FormValue("item_name")

    location := r.Form["location"]

    // // Form submitted
    // r.ParseForm() // Required if you don't call r.FormValue()
    // fmt.Println(r.Form["location"])

    insForm, err := db.Prepare("INSERT INTO master_code(item_code, item_name, location) VALUES(?,?,?)")

    fmt.Println(location)

    // names := []string{location}
    // fmt.Println(names)
    if err != nil {
        panic(err.Error())
    }
    insForm.Exec(item_code, item_name)
    insForm.Exec(location)
    log.Println("INSERT: Item Code: " + item_code + " | Item Name: " + item_name + "")
}
defer db.Close()
http.Redirect(w, r, "/", 301)

}

这是我的html:

<div class="form-group col-md-6">
    <label for="inputPassword4">Location</label><br>
    <div class="form-check form-check-inline">
        <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="location" value="Jakarta">
        <label class="form-check-label" for="inlineCheckbox1">Jakarta</label>
    </div>
    <div class="form-check form-check-inline">
        <input class="form-check-input" type="checkbox" id="inlineCheckbox2" name="location" value="Surabaya">
        <label class="form-check-label" for="inlineCheckbox2">Surabaya</label>
    </div>
    <div class="form-check form-check-inline">
        <input class="form-check-input" type="checkbox" id="inlineCheckbox3" name="location" value="Tangerang">
        <label class="form-check-label" for="inlineCheckbox2">Tangerang</label>
    </div>

1 个答案:

答案 0 :(得分:0)

让我们从HTML开始。要为复选框使用多个名称(如数组),您需要使用[[]”,以使PHP知道可以有多个发布值。 PHP也只会获取已选中复选框的值,而不会得到未选中复选框的值。我做了一个预览,tehplayground不允许您使用_POST,但是如果您复制代码,则可以在本地运行。

Preview