Help on SQL Query

I’ve been on this all day and I have not been able to figure it out. Not a lot about Golang but, sure I can get help here.

I’m trying to see if a user exists on my database and I did this:

func IsSignedUp(nk string)bool{
var nickVal string
var exists bool
db, err := sql.Open(“mysql”, “root:pass@/dbase”)
if err != nil{
fmt.Println(“Error occured while preparing abstrct DB:”, err)
}
defer db.Close()

stmt, err := db.Query("SELECT * FROM users WHERE nick = ", nk)//here
if err != nil{
    fmt.Println("Error at db.QUery:IsSignedUp", err)
}
for stmt.Next(){
    err := stmt.Scan(&nickVal)
    if err != nil{
         fmt.Printf("Error occured from dbase")
       }
       if nickVal == nk{
           exists = true
       }else{
           exists = false
       }
   }
   return exists

}

I got an error specific to the line

stmt, err := db.Query("SELECT * FROM users WHERE nick = ", nk)//here
if err != nil{
fmt.Println(“Error at db.Query:IsSignedUp”, err)
}

It says there is an error in the syntax. Please help with a method to do this. Thanks

You need a placeholder in your query for where to insert the variable, such as ? or $1. Consult the documentation for your MySQL driver.

1 Like

Try doing:
stmt, err := db.Query(“SELECT * FROM users WHERE nick=?”, nk)//here

Also its good practice to not hard code your mysql login credentials. Just read the string from a separate text file and concat the host, username, encrypted password, database name, etc. This will allow you to share your source code on say open source/team project and protect your login credentials.

1 Like

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