[solved] How to read All rows form Database and set in struct array

Hey Guys,
I write this code for read all rows form user table:

func GetAllUsers(db *sql.DB, w http.ResponseWriter, r *http.Request) {

	ctx := context.Background()
	users := make([]model.User, 0)

	rows, err := db.QueryContext(ctx, "select * from users")

	if err != nil {
		panic(err)
	}

	fmt.Println(rows)

	for rows.Next() {
		var user model.User

		if err := rows.Scan(&user); err != nil {
			log.Fatal(err)
		}
		users = append(users, user)
	}

	respondJSON(w, http.StatusOK, users)
}

but got this error:

sql: converting argument $1 type: unsupported type []model.User, a slice of struct

may please help me to fix this

1 Like

with help I found question:

func GetAllUsers(db *sql.DB, w http.ResponseWriter, r *http.Request) {

	ctx := context.Background()
	

	rows, err := db.QueryContext(ctx, "select * from users")

	if err != nil {
		panic(err)
	}

        users := make([]model.User, 0)
	for rows.Next() {
		var user model.User
		if err := rows.Scan(&user.Name, &user.Avatar, &user.Mobile, &user.BirthDay, &user.Identify, &user.Cart, &user.Credit, &user.Password, &user.Type, &user.Email, &user.Id); err != nil {
			log.Fatal(err)
		}

		users = append(users, user)
	}


	respondJSON(w, http.StatusOK, users)
}

I hope this be useful for someone.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.