When I use the get() method in codeigniter I get following query as result:
SELECT * FROM "table_users" WHERE "mail" = 'test#test.com'
instead of:
SELECT * FROM table_users WHERE mail = 'test#test.com'
This causes it to not work correctly with Oracle 11g as the double quotes should not go with the table name.
I got the following error:
Error Number: 942
ORA-00942: table or view does not exist
SELECT * FROM "table_usuarios" WHERE "correo" = 'test#test.com'
Filename: C:/xampp/htdocs/Tecnologico/system/database/DB_driver.php
Line Number: 691
I solved it, at least temporarily.
Editing the file system/database/DB_driver.php
into the query() function we add the following line:
$sql = str_replace('"',"",$sql);
Just before the comment:
// Run the Query
Related
I am trying to run a query that searches items in the Item table by how similar their title and description are to a value, the query is the following:
let items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`
However when the code is run I receive the following error:
error - PrismaClientKnownRequestError:
Invalid `prisma.$queryRaw()` invocation:
Raw query failed. Code: `42P01`. Message: `table "item" does not exist`
code: 'P2010',
clientVersion: '4.3.1',
meta: { code: '42P01', message: 'table "item" does not exist' },
page: '/api/marketplace/search'
}
I have run also the following query:
let tables = await prisma.$queryRaw`SELECT * FROM pg_catalog.pg_tables;`
Which correctly shows that the Item table exists! Where is the error?
After doing some light research, It looks like you possibly need double-quotes. Try
let items = await prisma.$queryRaw`SELECT * FROM "Item" ... blah blah
I say this because PostgreSQL tables names and columns default to lowercase when not double-quoted. If you haven't built much of your db, it may be worth wild to make all the tables and columns lowercase so that you won't have to keep adding double quotes and escaping characters.
References:
PostgreSQL support
Are PostgreSQL columns case sensitive?
I have the following C# code to select a column from a table that is on a linked server:
var query2 = $#"select [FileName] from [AMS_H2H].[H2H].[dbo].[FileReconciliation] where ProductCode = #productCode";
LayZConnection(); //make the db connection
var candidates = _dbConnection.Query<int>(query2, new { productCode = "ACHDH" });
When running it, I get the following error:
"Input string was not in a correct format."
If my query is instead the following, where I select all columns, it works:
var query2 = $#"select * from [AMS_H2H].[H2H].[dbo].[FileReconciliation]
What is the correct format to select just the FileName. Btw, the first query works fine from MSSMS.
You're specifying a type of int in Query<int>, which will cause Dapper to try and map the result of the query to an integer, however your query is returning a filename in select [FileName], which would suggest that it is a string.
Changing the type Query<string> should solve the issue.
More information on Dapper's Query method is available in Dapper's documentation
I have the following code which executes an oracle view as follows:
def run_query
connection.exec_query(
"SELECT * FROM TABLE(FN_REQRESP(#{type_param},
#{search_type_param},
#{tid_param},
#{last_param},
#{key_param},
#{tran_id_param},
#{num_param},
#{start_date_param},
#{end_date_param}))")
end
The output of the above query is as follows:
SELECT * FROM TABLE(FN_REQRESP('ALL',
'ALL_TRAN',
'100007',
'',
'',
'',
'',
TO_DATE('27-January-2017','dd-MON-yy'),
TO_DATE('31-January-2017','dd-MON-yy')))
The problem is that above query has a SQL injection vulnerability.
So, i tried to add a prepare statement as follows:
connection.exec_query('SELECT * FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))','myquery',[type_param,search_type_param,tid_param,last_param,key_param,tran_id_param,num_param,start_date_param,end_date_param])
I get the following error now:
NoMethodError: undefined method `type' for "'ALL'":String: SELECT *
FROM TABLE(FN_REQRESP(?,?,?,?,?,?,?,?,?))
It's the single quotes that messing it up I beleive. Is there a way to overcome this?
EDIT:
I tried NDN's answer and the error below:
OCIError: ORA-00907: missing right parenthesis: SELECT * FROM TABLE(FN_REQRESP('\'ALL\'',
'\'ALL_TRAN\'',
'\'100007\'',
'\'\'',
'\'\'',
'\'\'',
'\'\'',
'TO_DATE(\'01-February-2017\',\'dd-MON-yy\')',
'TO_DATE(\'10-February-2017\',\'dd-MON-yy\')'))
Looking at the source, binds gets cast in some magical way and you have to pass a named prepare: true argument as well.
It also used to work differently in older versions.
To save yourself the trouble, you can simply use #sanitize:
params = {
type: type_param,
search_type: search_type_param,
tid: tid_param,
last: last_param,
key: key_param,
tran_id: tran_id_param,
num: num_param,
start_date: start_date_param,
end_date: end_date_param,
}
params.each do |key, param|
params[key] = ActiveRecord::Base.sanitize(param)
end
connection.exec_query(
"SELECT * FROM TABLE(FN_REQRESP(#{params[:type]},
#{params[:search_type]},
#{params[:tid]},
#{params[:last]},
#{params[:key]},
#{params[:tran_id]},
#{params[:num]},
#{params[:start_date]},
#{params[:end_date]}))"
)
This is called Prepared Statement. In doc you can find an example how to use it.
I use R to read data from a Hana database. Some of the table names include backslashes, which forces me to use quotation marks. I cannot read these tables using R. Let me show you an example ...
This SQL works in Hana:
SELECT COUNT(*) FROM P3O."/BBB/BBB";
When I try to use the same code to read the data with R from the Hana database I get these errors:
library("RODBC")
channel <- odbcConnect("xxx",uid="xxx",pwd="xxx")
query <-
paste("'","SELECT COUNT(*) FROM P30.", "\"/BBB/BBB\"","'",sep="")
RAW_dataHana <- sqlQuery(channel, query)
close(channel)
I get following errors:
Syntax error or access violation;257 sql syntax error: incorrect
syntax near \"SELECT COUNT() FROM ... [2] "[RODBC] ERROR: Could not
SQLExecDirect ''SELECT COUNT() FROM P30.\"/BBB/BBB\"''"
I think it has something to do with the quotation, but when I check the code with this, I think I get the correct query:
x = paste("'","SELECT COUNT(*) FROM P30.", "\"/BBB/BBB\"", "'",sep="")
cat(x)
> cat(x)
'SELECT COUNT(*) FROM P30."/BBB/BBB"'
Just got now to check my RODBC test code...
The easiest way to handle the quoting is to enclose the query string in single quotes, e.g.:
sales_fact<-sqlQuery (ch, 'SELECT TOP 200 "ORDERID", "VAR_INDICATOR",
sum("ORDER_CNT") AS "ORDER_CNT",
sum("VARIANCE") AS "VARIANCE",
sum("VARIANCE_PCT") AS "VARIANCE_PCT",
sum("BUDGET") AS "BUDGET",
sum("ACTUAL") AS "ACTUAL"
FROM "_SYS_BIC"."test/ODERS_CV"
GROUP BY "ORDERID", "VAR_INDICATOR"')
This also works with paste():
queryText <- 'SELECT TOP 200 "ORDERID", "VAR_INDICATOR",
sum("ORDER_CNT") AS "ORDER_CNT",...'
queryText <- paste(sep = '', queryText, ' "_SYS_BIC"."test/ODERS_CV"
GROUP BY "ORDERID", "VAR_INDICATOR"')
Background
Framework: Codeignighter/PyroCMS
I have a DB that stores a list of products, I have a duplicate function in my application that first looks for the common product name so it can add a 'suffix' value to the duplicated product.
Code in my Products model class
$product = $this->get($id);
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
$new_product->name = $product->name . ' - ' . $count;
On the second line the application fails only when the $product->name contains quotes.
I was with the understanding that Codeignighter escaped all strings so I dont know why I get this error.
So I tried to use MySQL escape string function but that didn't help either.
The Error Message
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
var_dump
Below is the output of doing a var_dump on product->name before and after the line in question;
string 'Harry's Book' (length=12)
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Book%'' at line 3
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
Let's do some testing about this.
Here is what you are doing
$count = $this->db->like('name', $product->name)->get('products')->num_rows();
And i suspect $product->name contains this.
Harry's Book
As we know this is coming from the database table as you are using.
Where you are using the upper query mentioned it is wrapping it with
single quotes and producing this result.
SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
As you see it is escaping apostrophy to tell it is not end of string
Therefore escaping it with two slashes.One for apostrophy and one for being in single quote.
What you have to do is
Before assigning the parameter to query wrap it with double quotes.
$product_name = "$product->name";
And now pass it to query.
$count = $this->db->like('name', $product_name)->get('products')->num_rows();
The output will be this
SELECT * FROM `products` WHERE `name` LIKE '%Harry\'s Book%'
You see the differece here. It contains single slash now and the record will
be found.
Other answers didn't work for me, this does though:
$count = $this->db->query("SELECT * FROM `default_firesale_products` WHERE `title` LIKE '".addslashes($product['title'])."'")->num_rows();
Whenever CI Active Record mangles your queries you can always just put a raw query in instead and have full control.
Try this, using stripslashes() around $product->name:
$count = $this->db->like('name', stripslashes($product->name))->get('products')->num_rows();
CI automatically escapes characters with active records but I bet that it's already escaped if you entered it previously via active record in CI. So now it is doing a double escape.
Update: You may also want to try adding the following before you query:
$this->db->_protect_identifiers = FALSE;
Last try: try querying this way since it seems like the like active record is causing the error:
$like = $product->name;
$this->db->query("SELECT * FROM `products` WHERE `name` LIKE '%$like%'");