what is wrong with this sql query? - sql

what is wrong with this sql query. i cant figure it out.
$query = "SELECT *
FROM tagPairs
WHERE (tag1Id IN ($tag1Id, $tag2Id))
AND (tag2Id IN ($tag1Id, $tag2Id))";
error code:
Couldn't execute query: 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 ' ))
AND (tag2Id IN (, ))' at line 3
thanks in advance!

$tag1Id and $tag2Id are both null, or empty strings. The simplest solutions is probably to explicitly cast them into numerical values:
$tag1Id = intval($tag1Id);
$tag2Id = intval($tag2Id);
$query = "SELECT *
FROM tagPairs
WHERE (tag1Id IN ($tag1Id, $tag2Id))
AND (tag2Id IN ($tag1Id, $tag2Id))";

$tag1Id and $tag2Id are empty.
That's why your error says (tag2Id IN (, )).

Your $tag1Id and $tag2Id are empty strings. Assign a value to them and it should work fine.
Also, selecting * is a bad idea. Select the columns you need explicity.

Related

Rails query to SQL statement

I'm trying to write an write this:
Team.last.players.sum("goals")
erb:
SELECT SUM("players"."goals")
FROM "players"
WHERE "players"."team_id" = $1 [["team_id", 2]]
how to rewrite this so that I could use it in a method:
def sql_search
sql = "SELECT SUM \"players\".\"goals\" FROM \"players\" WHERE \"players\".\"team_id\" = $1 [[\"team_id\", #{self.id}"
connection.execute(sql);
end
keep getting this error:
PG::SyntaxError: ERROR: syntax error at or near "."
LINE 1: SELECT SUM "players"."goals" FROM "players" WHERE "players"....
Any ideas would be appreciated
You don't need to add \" in sql statement, just remove them.
def sql_search
sql = "SELECT sum(goals) FROM players WHERE team_id = #{self.id};"
connection.execute(sql);
end
Is there some reason that you want to hard code the SQL query? It's generally bad practice to use string interpolation to insert parameters to SQL queries because of SQL injection attacks. Instead it's recommended to use ActiveRecord's SQL query parameter binding like this:
user_input = 5
Player.where('team_id = ?', user_input).sum(:goals)
Basically what this does is insert the parameter 5 after sanitization. This means you're safe from attacks where a hacker attempts to insert arbitrary SQL into parameter variables attempting to return sensitive data or delete data entirely!

[ODBC Microsoft Access Driver]COUNT field incorrect

$q = 'INSERT INTO MyTable(proddesc, qnty, PriceH, PriceA, PriceL) VALUES(?,?,?,?,?)';
$sth = odbc_prepare($dbConn, $q);
$success = odbc_execute($sth, array(my 5 variables that are not null));
It gives me the above error - [ODBC Microsoft Access Driver] COUNT field incorrect. I know that the query is correct because I ran it in Access and it was fine. I think I may be using the prepare/execute statements incorrectly.
I also encountered this now and the solution I did to fix it is to quote the variables properly.
Try printing your $q and you will see if it needs to be quoted.
You can try these too:
INSERT INTO TABLE -- quote db and table names using (`) "grave accent" character
VALUES( 'Fed''s' ) -- quote the apostrophes

Active record query failed - Escape quote from query

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%'");

Hibernate createSQLQuery and Toad SQL query return different results - parameter problems?

I'm a newbie at Hibernate so excuse me if some of this is glaringly obvious but it's been a very, very long day. I am trying to create and execute a simple query in Hibernate and Toad/Oracle.
The Toad/Oracle sql reads:
select
count(*)
from
fpps_owner.fee_claim_payment_lines l,
fpps_owner.fee_claim_payments p
where
l.fee_claim_payment_id = p.fee_claim_payment_id and
p.claim_index = 87167895
The above returns 10 records, which is correct
The following Java code returns 0 records, which is NOT correct
String sLinesAvailable =
"select count(*) from " +
"fpps_owner.fee_claim_payment_lines l, fpps_owner.fee_claim_payments p " +
"where " +
"l.fee_claim_payment_id = p.fee_claim_payment_id and p.claim_index = :id";
Query qLinesAvailable = em.createNativeQuery(sLinesAvailable);
qLinesAvailable.setParameter("id", "87167895"); // fails
qLinesAvailable.setParameter("id", 87167895); // fails
List<Object> out = (List<Object>) qLinesAvailable.getResultList();
BigDecimal x = (BigDecimal) out.get(0);
Returns 0 records. Using .getSingleResult() also returns 0 records.
What am I missing here?
Any help would be GREATLY appreciated!
If you are not seeing any malformed query errors, it seems like the parameter is not binding correctly.
To debug, I'd print out that SQL statement the line after you set the parameter. This is the only way you can see the SQL after the parameter is set in order to compare it with Toad.
What does your binding file look like? Maybe you have a different name in there for the ID, so it's not able to find it based on the name. Trying binding with the parameter's order value, just as a test.
This might give some ideas: http://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Best of luck! We've all been there :)
What happens when you try:
(Number) query.getSingleResult();
Your query isn't returning a list, but rather just a count.
Good luck.

MySQL Query Error

I have an error with this sentence:
...
WHERE title LIKE '%$title%' OR text LIKE '%$title%'
AND (price BETWEEN $minprice AND $maxprice)
AND catid = $catid ORDER BY id DESC
Error:
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 'AND ) AND cat' at line 34
I did something wrong?
Evaluating "$maxprice" gives an empty string, probably because the variable $maxprice it is not defined. It could be a typo, or that you forgot to set a value for this variable.
Check your $maxprice Variable - it seems to be empty.