I have inserted dummy data into the database.
The sample print function prints 13 and its square as per the code in the console. But I need to pass the entire data to the HTML template(index) where I can see a table of all the numbers passed with their respective square number.
How to pass this data in index HTML?
Number x Number = SquareNumber
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
...
and so on.
func main() {
db, err := sql.Open("mysql", "root:@/godb")
if err != nil {
panic(err.Error())
}
defer db.Close()
stmtIns, err := db.Prepare("INSERT INTO squarenum VALUES(?, ?, ? )") // ? =
placeholder
if err != nil {
panic(err.Error()) }
defer stmtIns.Close()
stmtOut, err := db.Prepare("SELECT squareNum FROM squareNum WHERE number =
?")
if err != nil {
panic(err.Error())
}
defer stmtOut.Close()
for i := 1; i < 50; i++ {
_, err = stmtIns.Exec(0,i, (i * i))
if err != nil {
panic(err.Error())
}
}
err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
tRes:=pageData{}
tRes.SquareNum=squareNum
fmt.Printf("The square number of 13 is: %d
", squareNum)
// Query another number.. 1 maybe?
err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
fmt.Printf("The square number of 1 is: %d
", squareNum)
http.HandleFunc("/",idx)
http.ListenAndServe(":8888", nil)
}
func idx(w http.ResponseWriter, r *http.Request) {
pd := pageData{
SquareNum: squareNum,
}
err := tpl.ExecuteTemplate(w, "index.html", pd)
if err != nil {
log.Println("LOGGED", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}