Reputation: 513
I am trying to pass the value of textInput into MySQL query.
The first question is what is the right syntax for the LIKE operator combined with textInput, when using MySQL as the driver? Where should I put the %% in the query statement?
Second is how best can I capture the reactivity of the textInput, to be able to pass it to the query and create a table?
library(shiny)
library(DBI)
library(RMySQL)
server <- shinyServer(function(input, output, session) {
con <- dbConnect(MySQL(), user='user', port = 3306, password='pwd', dbname='db', host='host' )
on.exit(dbDisconnect(con), add = TRUE)
output$tableview <- renderTable({
con <- dbConnect(MySQL(), user='user', port = 3306, password='pwd', dbname='db', host='host' )
on.exit(dbDisconnect(con), add = TRUE)
table <- reactive({
dbGetQuery(con, statement =
paste0(" SELECT author, title, publicationDate, FROM publications
WHERE publications.abstract LIKE %'",input$textSearch,"'% ")
)
})
table()
})
session$onSessionEnded(function() { dbDisconnect(con) })
})
ui_panel <-
tabPanel("Text Input Test",
sidebarLayout(
sidebarPanel(
textInput("textSearch", " Search for keyword", ''),
br(),
submitButton("Update Table View"),
br()
),
mainPanel(
tabsetPanel(tabPanel("Table",tableOutput("tableview"))
)
)
))
ui <- shinyUI(navbarPage(" ",ui_panel))
runApp(list(ui=ui,server=server))
Similar questions How to read a TextInput in ui.R, process a query with this value in global.R and show in server.R using Shiny which deals with output and dealing with a global file which I do not have in my case.
Any insight will be welcome.
Upvotes: 0
Views: 246
Reputation: 439
Your current code should construct this SQL:
SELECT ... FROM publications WHERE publications.abstract LIKE %'test'%
The issue: %
should be inside ''
.
Updated line:
paste0("SELECT author, title, publicationDate, FROM publications WHERE publications.abstract LIKE '%",input$textSearch,"%' ")
Then it should construct this SQL:
SELECT author, title, publicationDate, FROM publications WHERE publications.abstract LIKE '%test%'
For testing, I would recommend to render the generated SQL as text with renderText()
and verbatimTextOutput()
and see the outcome.
You can also consider to use glue package to construct SQL queries safely.
For your second question, Action Buttons article might be useful.
Upvotes: 1