I have few functions to connect to a database and fetch results. My question is why fetch not working?
My database structure looks like
My main.go code is
package main
import (
"database/sql"
"log"
"net/http"
"text/template"
_ "github.com/go-sql-driver/mysql"
)
type maintable struct {
Id int
Location string
Picname string
Malefemale string
Name string
Country string
Connections int
}
func dbConn() (db *sql.DB) {
db, err := sql.Open("mysql", "root:@/test_db")
if err != nil {
panic(err.Error())
}
return db
}
var tmpl = template.Must(template.ParseGlob("form/*"))
func Index(w http.ResponseWriter, r *http.Request) {
db := dbConn()
selDB, err := db.Query("SELECT * FROM main_table ORDER BY user_id DESC")
if err != nil {
panic(err.Error())
}
defer selDB.Close()
maint := maintable{}
res := []maintable{}
for selDB.Next() {
var id, connections int
var name, country, location, picname, malefemale string
err = selDB.Scan(&id, &name, &country, &location, &picname, &malefemale, &connections)
if err != nil {
panic(err.Error())
}
maint.Id = id
maint.Name = name
maint.Country = country
maint.Location = location
maint.Picname = picname
maint.Malefemale = malefemale
maint.Connections = connections
res = append(res, maint)
}
tmpl.ExecuteTemplate(w, "Index", res)
defer db.Close()
}
func Show(w http.ResponseWriter, r *http.Request) {
db := dbConn()
nID := r.URL.Query().Get("user_id")
selDB, err := db.Query("SELECT * FROM main_table WHERE user_id=?", nID)
if err != nil {
panic(err.Error())
}
maint := maintable{}
for selDB.Next() {
var id, connections int
var name, country, location, picname, malefemale string
err = selDB.Scan(&id, &name, &country, &location, &picname, &malefemale, &connections)
if err != nil {
panic(err.Error())
}
maint.Id = id
maint.Name = name
maint.Country = country
maint.Location = location
maint.Picname = picname
maint.Malefemale = malefemale
maint.Connections = connections
}
tmpl.ExecuteTemplate(w, "Show", maint)
defer db.Close()
}
log.Println("Server started on: http://localhost:3000")
http.HandleFunc("/", Index)
http.HandleFunc("/show", Show)
http.ListenAndServe(":3000", nil)
}
And my show.tmpl code is looks like
{{ define "Show" }}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Golang Mysql Curd Example</title>
<meta charset="UTF-8" />
</head>
<body>
<h1>Golang Mysql Curd Example</h1>
<a href="/">HOME</a> |
<a href="/new">NEW</a>
<h2> Register {{ .Id }} </h2>
<p>Name: {{ .Name }}</p>
<p>Picture name: {{ .Picname }}</p>
<p>Picture location: {{ .Location }}</p>
<p>Gender: {{ .Malefemale }}</p>
<p>Country: {{ .Country }}</p>
<p>User connections: {{ .Connections }}</p>
<br /> <a href="/edit?user_id={{ .Id }}">Edit</a></p>
</body>
</html>
{{ end }}
Do I need create array and append all results to array? Is there other way to display multi rows?