Reputation: 433
I am using selectInput()
to fetch a list of months from a database and using them to show a drop down menu on shiny.
month <- dbGetQuery(con, statement =
paste( "select distinct month
from table
order by month
"))
selectInput("month",
"month",
sort(unique(month$month)),
selected = NULL)
I am then using the above input in another query:
server <- shinyServer(function(input, output) {
output$graph <- renderPlot({
ctab <- dbGetQuery(con, statement =
paste("select colum1, column2
from table
where month_of_year_name = ",input$month,"
"))
output$graph2 <- renderPlot({
})
})
The problem is that the selectInput
gives the month as Jan and I'd like it to give it as 'Jan'.
Upvotes: 1
Views: 684
Reputation: 29417
Personally I like using regex
to create my queries, I think it gives very good flexibility and its quite readable
data <- reactive({
query <- 'select colum1, column2 from table where month_of_year_name = "MONTH"'
query <- gsub("MONTH",input$month,query)
query <- noquote(query)
dbGetQuery(con,query)
})
output$graph <- renderPlot({
data()
})
Upvotes: 0
Reputation: 17279
I would recommend using sqlInterpolate
to protect against SQL Injection attacks
server <- shinyServer(function(input, output) {
output$graph <- renderPlot({
ctab <- dbGetQuery(con,
statement =
sqlInterpolate(con,
"select colum1, column2
from table
where month_of_year_name = ?month",
month = input$month))
})
})
Upvotes: 2
Reputation: 25435
You can simply put '
in your strings to be pasted, when you use "
to encapsulate strings. Example:
ui <- fluidPage(
selectInput('month','months: ', c('Jan','Feb','Mar')),
h3('old_query'),
textOutput('old_query'),
h3('new_query'),
textOutput('new_query')
)
server <- shinyServer(function(input, output) {
output$old_query <- renderText({
paste("select colum1, column2
from table
where month_of_year_name = ",input$month,"")
})
output$new_query <- renderText({
paste("select colum1, column2
from table
where month_of_year_name = '",input$month,"'")
})
})
shinyApp(ui,server)
Hope this helps!
Upvotes: 1