Database LOOKUP

This is a simple lookup function
It returns the value of a simple database query

Public Function Findfield(campo as string, chiave as string, table as string, valore as String, optional filtro as string = "") as string
  dim sql as string
  
  // DEBUG PER VALORE 
  // aggiunge nel caso i caratteri escape per mysql 
  valore = replaceall(valore,chr(8),"\\b")
  valore = replaceall(valore,chr(10),"\
")
  valore = replaceall(valore,chr(13),"\\r")
  valore = replaceall(valore,chr(9),"\\t")
  
  if filtro.trim <> "" then
    filtro = replaceall(filtro,"where","AND")
    filtro = Replaceall(filtro,"WHERE","AND")
  end if
  
  if filtro.trim <> "" then
    sql = "select distinct * from " + table + " where " + campo + " = '" + valore + "' " + filtro + ";"
  else
    sql = "select distinct * from " + table + " where " + campo + " = '" + valore + "';"
  end if
  
  ' apro il db
  
  dim db as new DBKoala(procedure.dbdatabasetype) // Change with our preferred database
  db.DatabaseName = procedure.dbname
  db.Host = procedure.dbhost // vediamo per ODBC
  db.Port = procedure.dbport
  db.Username = procedure.dbusername
  db.Password = procedure.dbpassword
  
  If Not db.Connect() then
    msgbox("errore nella lettura del database : " + db.errorMessage + ". Prego contattare l'autore del programma")
    return ""
    exit Function
  else
  
   Dim rslookup As RecordSet
    rslookup = db.SQLSelect(sql)
    
    ' ora controllo se ho i record
    if rslookup.eof then
      Return ""
      exit function
    else
      return rslookup.field(chiave).utfValue
    end if
  end if
End Function