I need to go through an html forms input values and place them into an mysql datbase. Which I'm currently using r.Form
to get a map. So that i don't have to use r.Form.Get("date")
for each which works but when i try to put the values into a database. It compiles just fine but i get sql: converting argument #0's type: unsupported type []string, a slice
after i click submit in the browser. I can get around this by doing
`date := strings.Join(m["date"], "")`
but doing that for 30+ values especially since some of the submited values will be created from previous database entries using html templates. If i have to change or add more later seems like there must be a more efficient way I've seen for key, val := range m {}
but unfortunately I've only been doing this for about a week and i can't figure out how to keep the values and change the variable they get set to after each iteration. So that after
for key, val := range m {
x := m[key]
}
so that it will put out the equivalent
keyname := keyvalue
changing the keyname each time to be the same as the keyname in the map ie
date := 2015-8-13
time := 18:56:11
or if there's an easier way around this error then to create a varible for each one.
An HTML form can have multiple values for a single key. This is why the request form field is defined to be a map of string slices. The request Form is declared as
Form url.Values
and url.Values is declared as
type Values map[string][]string
You can access the first value for a key using:
var value string
if values := req.Form[key]; len(values) > 0 {
value = values[0]
}
The url.Values Get helper method simplifies this code to:
value := req.Form.Get(key)
The http.Request FormValue helper method simplifies it a bit more:
value := req.FormValue(key)
You iterate through keys and values using:
for key, values := range req.Form {
for _, value := range values {
fmt.Println(key, value)
}
}
If you want to iterate over the first value for a key, then use this code:
for key, values := range req.Form {
if len(values) > 0 {
value := values[0]
fmt.Println(key, value)
}
}
Before accessing req.Form, call req.ParseForm to parse the query string and request body.