我从MySQL表中获取了所有数据,并使用“log”函数打印了它,但我需要在HTML页面上打印它。我只能打印一列。我想打印所有产品数据。我该怎么做?
简而言之:我想列出商店页面的所有产品,但我只能列出一种产品。(我将添加数百种产品。目前,我的表中只有3种产品。
我已经2天没有解决了它,如果你能帮忙,我会很高兴。非常感谢...转到文件
package main
import ( "database/sql" "fmt" "log" "net/http" "text/template"
_ "github.com/go-sql-driver/mysql"
)
type product struct { ID int Name string Stock int Price float32 }
var products product
func handler(w http.ResponseWriter, r *http.Request) {
products = product{
ID: products.ID,
Name: products.Name,
Stock: products.Stock,
Price: products.Price,
}
appointment, _ := template.ParseFiles("ot.html")
appointment.Execute(w, products)
}
func main() { fmt.Println("Go MySQL Tutorial")
sqlType := "mysql"
sqlUsn := "root"
sqlPass := "2582064"
sqlDatabase := "gowdb"
db, err := sql.Open(sqlType, sqlUsn+":"+sqlPass+"@/"+sqlDatabase)
if err != nil {
panic(err.Error())
}
defer db.Close()
results, err := db.Query("SELECT * FROM products")
if err != nil {
panic(err.Error())
}
for results.Next() {
err = results.Scan(&products.ID, &products.Stock, &products.Price, &products.Name)
if err != nil {
panic(err.Error())
}
log.Println(products.Name)
}
if err != nil {
panic(err.Error())
}
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
网页
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>PRODUCT 1</h1>
<div>NAME: {{.Name}}</div>
<div>PRICE: {{.Price}}</div>
<div>STOCK: {{.Stock}}</div>
<div>ID: {{.ID}}</div>
<div>BUY FROM: xxx.com</div>
<h1>PRODUCT 2</h1>
<div>NAME: {{.Name}}</div>
<div>PRICE: {{.Price}}</div>
<div>STOCK: {{.Stock}}</div>
</body>
</html>
日志上的输出(没关系)
电子掩模丝状面罩气滴面罩
网页上的输出
产品1名称:空投面具价格:19库存:2 ID:2 从中购买:xxx.com
产品2名称:空投面具价格:19库存:2 ID:2 从中购买:xxx.com
产品3名称:空投面具价格:19库存:2 ID:2 从中购买:xxx.com
慕容708150
相关分类