我正在尝试使用golang将网页中“反馈”部分的星级评定存储到数据库中。
在Home.html中,我编写了用于星级评定的html代码。
<div class="stars">
<form action="/feedback" method="POST">
<input class="star star-5" id="star_5" type="radio" value="5" name="star"/>
<label class="star star-5" for="star_5"></label>
<input class="star star-4" id="star_4" type="radio" value="4" name="star"/>
<label class="star star-4" for="star_4"></label>
<input class="star star-3" id="star_3" type="radio" value="3" name="star"/>
<label class="star star-3" for="star_3"></label>
<input class="star star-2" id="star_2" type="radio" value="2" name="star"/>
<label class="star star-2" for="star_2"></label>
<input class="star star-1" id="star_1" type="radio" value="1" name="star"/>
<label class="star star-1" for="star_1"></label>
<label for="isRate"><span></span></label>
</form>
</div>
在main.go中,我编写了函数
var CDSID string
var Rating int
var CreateDate string
var rate int
func createUser(w http.ResponseWriter, r *http.Request) {
//stmt, err := db.Query("INSERT tbl_fdback SET CDSID='DDUTTA3', CreateDate=getdate(), Rating=?")
stmt :="INSERT INTO tbl_fdback VALUES($1,$2,$3)"
if err != nil {
log.Fatal("there was an error:", err.Error())
return
}
isRate := r.FormValue("star")
if (isRate == "one") {
rate = 1
}else if (isRate == "two"){
rate = 2
}else if (isRate == "three") {
rate = 3
}else if (isRate == "four") {
rate = 4
}else if (isRate == "five") {
rate = 5
}else {
fmt.Println("Work harder")
}
_, err := db.Exec(stmt,"DDUTTA3",CreateDate,rate)
if err != nil {
log.Println(err)
return
}
}
func main() {
flag.Parse()
dsn := "server=fcdb1198;user id=prxqamydb;password=dbnms#666"
db, err := sql.Open("mssql", dsn)
if err != nil {
fmt.Println("Cannot connect: ", err.Error())
return
}
err = db.Ping()
if err != nil {
fmt.Println("Cannot connect1: ", err.Error())
return
}
defer db.Close()
http.HandleFunc("/feedback", createUser)
http.HandleFunc(STATIC_URL, StaticHandler)
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatalf("Error starting HTTP server: %v", err)
}
}
最佳答案
如果我说对了,您的星级评定值就是字符串,例如:“1”,“2” ...“5”(由于input class="star star-5" id="star_5" type="radio" value="5"
而不是“one”,“two” .. etc),因此您需要转换isRate
值:
rate, _ := strconv.Atoi(isRate)
并获取
rate
中的int值以传递SQL语句。