Is this SQL valid? - sql

I am still new to implementing joins in my db_design and i am not sure if, at all this SQL is valid.
"SELECT * FROM notes JOIN small_note ON notes_id = '$id' AND authname = '$author' AND bookname = '$book' AND user = '$username'"
A bit easier to read like this:
"SELECT * FROM notes
JOIN small_note ON notes_id = '$id'
AND authname = '$author'
AND bookname = '$book'
AND user = '$username'";

No it isn't.
You need to specify the join columns for both tables, and you need to make sure you use a correct WHERE clause (which is missing from your query).
This may be more suitable:
SELECT * FROM notes n
JOIN small_note sn
ON n.notes_id = sn.notes_id
WHERE notes_id = '$id'
AND authname = '$author'
AND bookname = '$book'
AND user = '$username'

I think you need to replace your first AND with WHERE.

No, your $id should be the columnname that holds the reference to the other table. That's not a variable, that's a columnname

Related

R shiny SQL database - reactive filtering - best practice?

New to R shiny and SQL
I have made some reactive dashboards but none yet using SQL database connection.
Here is my toy:
The database is the MySQL world database.
I want to join various tables and show some columns from each, but I want to be able to filter by Language found in the CountryLanguage table.
My WHERE statement doesn't work.
Current code:
ui <- fluidPage(
numericInput("nrows", "Enter the number of rows to display:", 5),
selectizeInput("inputlang", label = "Language", choices = NULL, selected = NULL, options = list(placeholder = "Please type a language")),
tableOutput("tbl")
)
server <- function(input, output, session) {
output$tbl <- renderTable({
conn <- dbConnect(
drv = RMySQL::MySQL(),
dbname = "shinydemo",
host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
username = "guest",
password = "guest")
on.exit(dbDisconnect(conn), add = TRUE)
dbGetQuery(conn, paste0(
"SELECT City.Name, City.Population, Country.Name, Country.Continent, CountryLanguage.Language, CountryLanguage.Percentage
FROM City
INNER JOIN Country on City.CountryCode = Country.Code
INNER JOIN CountryLanguage on Country.Code = CountryLanguage.CountryCode
WHERE CountryLanguage.Language = reactive({get(input$Selectize)})
LIMIT ", input$nrows, ";"))
})
}
shinyApp(ui, server)
I did not expect that code to work, but tried anyway. I suspect I can't pass an R command from within a dbGetQuery because it is expecting SQL syntax only. Is that correct?
So... what is the best way to set something like this up? I imagine I could make the joined selected stuff into a dataframe like
df <-dbGetQuery ( SELECT & JOIN)
dffilter <- df %>% filter ()
But is that going to make things super slow if the dataset is still quite large?
What would be the best practice here?
Having reactive(...) in a string is not evaluated, it's just a string. Further, DBI is not using glue on the query, so {get(...)} will do nothing.
You define the input as input$inputlang but in your reactive, you reference input$Selectize, I think that's a mistake.
You may want to consider parameterized queries vice constructing query strings manually. While there are security concerns about malicious SQL injection (e.g., XKCD's Exploits of a Mom aka "Little Bobby Tables"), it is also a concern for malformed strings or Unicode-vs-ANSI mistakes, even if it's a single data analyst running the query. Both DBI (with odbc) and RODBC support parameterized queries, either natively or via add-ons.
While this does not work for the LIMIT portion, it is useful for most other portions of a query. For that limit part, the req(is.numeric(input$nrows)) should be a reasonable check to ensure inadvertent injection problems.
Try this:
output$tbl <- renderTable({
req(is.numeric(input$nrows), input$inputlang)
conn <- dbConnect(
drv = RMySQL::MySQL(),
dbname = "shinydemo",
host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
username = "guest",
password = "guest")
on.exit(dbDisconnect(conn), add = TRUE)
dbGetQuery(conn, paste("
SELECT City.Name, City.Population, Country.Name, Country.Continent, CountryLanguage.Language, CountryLanguage.Percentage
FROM City
INNER JOIN Country on City.CountryCode = Country.Code
INNER JOIN CountryLanguage on Country.Code = CountryLanguage.CountryCode
WHERE CountryLanguage.Language = ?
LIMIT ", input$nrows),
params = list(input$inputlang))
})

INNER JOIN with Where condition not working

I have a SQL query in C# ASP.NET MVC, it works well without WHERE condition, but with a WHERE condition, it doesn't work.
Here is SQL statement:
string strSQL = "SELECT u.USERID, u.NAME, io.CHECKTIME, io.CHECKTYPE, io.SENSORID
FROM USERINFO u
INNER JOIN CHECKINOUT io ON u.USERID = io.USERID
WHERE u.NAME = " + conditionSearch.NAME;
With conditionSearch.NAME is a variable from a view, I checked it, it's OK with a value need to search.
Could you please show me what is wrong in this WHERE condition? Thanks you!
The immediate fix here would be to put the name in the WHERE clause inside single quotes, to make a string literal:
string strSQL = "SELECT u.USERID, u.NAME, io.CHECKTIME, io.CHECKTYPE, io.SENSORID
FROM USERINFO u INNER JOIN CHECKINOUT io ON u.USERID = io.USERID
WHERE u.NAME = '" + conditionSearch.NAME + "'";
However, doing a direct concatenation to form a SQL query string is usually seriously bad practice. A much better approach would be to use a prepared statement, with a placeholder for the name. That is, use a query looking something like:
SELECT u.USERID, u.NAME, io.CHECKTIME, io.CHECKTYPE, io.SENSORID
FROM USERINFO u
INNER JOIN CHECKINOUT io
ON u.USERID = io.USERID
WHERE u.NAME = ?;
Then, let your database worry about how to bind the name parameter correctly.
The immediate fix here would be to put the name in the WHERE clause inside single quotes, to make a string literal:
Hi Tim, Thank for reply. I tried with a exact a name have in db with single quotes, but the result still return null.
oh, but I tried with your solution ('" + conditionSearch.NAME + "'") and it work perfectly.
Thanks you so much!

How to sanitize join params inside a controller in Rails 4?

Is this, the best way to sanitize 'join' params inside a Controller in Rails 4?
assume:
user_name = params[:user_name]
.
# That's the only way that I can figure this out:
#result = Agenda.joins("LEFT JOIN meetings AS me ON meetings.agenda_id = agendas.id WHERE me.name = #{Agenda.sanitize(user_name})"
I have tried this but don't works because 'joins' expect tables after each ',':
#result = Agenda.joins("LEFT JOIN meetings AS me ON meetings.agenda_id = agendas.id WHERE me.name = ?", user_name)
Note:
This is just a bit of the code to explain the problem, in the full code I really have to use the LEFT JOIN.
I found a better solution using
Model.send(:sanitize_sql_array, < query >)
eg:
user_name = params[:user_name]
join = "LEFT JOIN meetings AS me
ON meetings.agenda_id = agendas.id
WHERE me.name = ?", user_name)"
join = Agenda.send(:sanitize_sql_array,join)
#result = Agenda.joins(join)
In this format, you can use as many parameters as you need with any type of query.

How can i user join on this SQL?

okay i have got this sql statement which someone helped me on here to make this statement the only problem im facing that i want catDesc from te_category table to be appear on my 'Category' table on main page but instead of that i'm getting catID from te_events
This is the code i got from stackoverflow.
$sql = "SELECT * FROM te_events
JOIN te_venue
ON te_venue.venueID = te_events.venueID
WHERE te_events.eventID = $eventID";
this my te_event table screenshot http://prnt.sc/d8e7i1
this is my te_category screenshot http://prntscr.com/d8e87e
I have tried anything but couldn't get what i want please HELP !
use this query:
$sql = "SELECT * FROM te_events
JOIN te_venue
ON te_venue.venueID = te_events.venueID
JOIN te_category ON te_category.catID = te_events.catID
WHERE te_events.eventID = $eventID";

Codeigniter Sql Error

function get_result_professions($key_word)
{
$sql = "SELECT users.name FROM users
inner join users_has_professions on users_has_professions.users_id = users.id
inner join professions on users_has_professions.professions_id = professions.id
where professions.key_word = ? ";
return $this->db->get()->query($sql, $key_word);
}
When I execute this code I receive the following error:
A Database Error Occurred
Error Number: 1096
No tables used
SELECT *
Filename: /var/www/expertt/models/search_model.php
Line Number: 31
How can I solve this problem? Thanks in advance.
$this->db->get() must contain an table name. in your case you want to remove it sindse you have an custom query so your function wil look like this:
function get_result_professions($key_word)
{
$sql = "SELECT users.name FROM users
inner join users_has_professions on users_has_professions.users_id = users.id
inner join professions on users_has_professions.professions_id = professions.id
where professions.key_word = '$key_word' ";
return $this->db->query($sql);
}
The $this->db->get() method in CodeIgniter's Active record requires a table name parameter (see the Active Record Documentation for more info) when used to query a table, unless you have previously build up the query using one of the other provided methods.
Usually when building up joins like you are doing you would use the select/ join methods provided by Active Record, like so
$this->db->select('users.name')->from('users')
->join('users_has_professions', 'users_has_professions.users_id = users.id')
->join('professions', 'users_has_professions.professions_id = professions.id')
->where('professions.key_word', $key_word);
(untested as I don't have your database to run it against)
You can then use the $this->db->get() method to retrieve the results like so
$results = $this->db->get();
foreach($query->result() as $row) {
//code here
}