-1

While we write a web application, we will use SQL prepare instead of concat SQL strings to avoid SQL injection. For example:

sql.exec("select * from user where user_id=?", user_id)

But how to write prepare WHERE...IN in SQL? For example:

sql.exec("select * from user where user_id in ?", user_ids)

If it is impossible. What is the proper way to avoid SQL injection in such a situation?

Thanks.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Bin Wang
  • 2,697
  • 2
  • 24
  • 34
  • Maybe I'm not clear. I'm not asking the way in PHP. I'd like to know if there are some general ways in the language who supports the MySQL driver. – Bin Wang Jun 11 '14 at 07:22
  • What is the application host language? Note that most drivers don't support array parameters, so the essential answer is the same - construct a list of replacement variables, then bind the values. – Clockwork-Muse Jun 11 '14 at 12:22
  • @Clockwork-Muse I'm using Golang for now. – Bin Wang Jun 11 '14 at 13:24
  • How about: `sql.exec("select * from user where user_id in (?)", "1,2,3,4")`? – nvcnvn Jun 11 '14 at 16:53

1 Answers1

0

change user_ids string to id array:

idArr = strings.Split(user_ids, ",")

create sql:

vals := []interface{}{}
sqlStr := "select * from user where user_id in ("
for _,v := range idArr {
    vals = append(vals, v)
    sqlStr += "?,"
}
sqlStr = strings.TrimRight(sqlStr, ",")
sqlStr += ")"

stmt, err := db.Prepare(sqlStr)
if err!=nil{
    return err
}
defer stmt.Close()

rows, err := stmt.Query(vals...)
leiyonglin
  • 6,474
  • 12
  • 36
  • 41