PDO statement error for "SUM" - sql

I have a query that im trying to collect tallys from fields in one query to avoid querying 4 times i added them all into one query.
But i am getting this error:
SQLSTATE[42000]: Syntax error or access violation: 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
')) as english,
sum(if(class='2')) as science,
sum(if(class='3')) as french
F' at line 3
I'm not sure how the syntax is meant to be for this so was hopeing some one might know... my query is this:
$stmt = $pdo->prepare("SELECT
count(id) AS total,
sum(if(class=?)) as english,
sum(if(class=?)) as science,
sum(if(class=?)) as french
FROM school");
try{
$stmt->execute(array(1,2,3));
} catch (PDOException $e){
echo $e -> getMessage(); exit;
}
Does any one know the correct syntax for this ?

At least, you have missed a right bracket in each sum line.
Then, Im not sure about if(..,..,..) statement, I usually write CASE WHEN (condition) THEN expr1 ELSE expr2 END

Related

Laravel - SQLSTATE[42000] - UNION

I am making a UNION between these two queries:
$first =
DB::table('pedido')
->select(DB::raw('date(fecha_pago) as fecha'),DB::raw('sum(subtotal) as ingreso'),DB::raw('0 as egreso'))
->where('idestado','=','2')
->groupBy(DB::raw('date(fecha_pago)'));
$second =
DB::table('egreso')
->select(DB::raw('date(fecha) as fecha'),DB::raw('0 as ingreso'),DB::raw('sum(monto) as egreso'))
->groupBy(DB::raw('date(fecha)'));
$final_query=
DB::select(DB::raw('date(fecha),sum(ingreso) as ingreso,sum(egreso) as egreso'))
->union($first)->union($second)
->groupBy(DB::raw('date(fecha)'))
->get();
I get the error:
SQLSTATE[42000]: Syntax error or access violation: 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 'date(fecha),sum(ingreso) as ingreso,sum(egreso) as egreso' at line 1 (SQL: date(fecha),sum(ingreso) as ingreso,sum(egreso) as egreso)
DB::select() executes a raw query, unlike DB::table()->select() which is used to define fields for the query builder to select.
You're missing the DB::table() in your final query, without it, you won't be using the query builder and you'll actually be running a query of just date(fecha),sum(ingreso) as ingreso,sum(egreso) as egreso.
https://laravel.com/docs/5.6/queries#selects

Syntax Error In Query with selectRaw and time diff

please advice how to correct this query
$no_of_hours = DB::Table('shifts')
->where('time_sheet_id','=', $timesheet_id->id)
->selectRaw("SELECT time(sum(TIMEDIFF( 'shift_end_time', 'shift_start_time' )))")
->get();
return $no_of_hours;
im getting following error
SQLSTATE[42000]: Syntax error or access violation: 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 'SELECT time(sum(TIMEDIFF( 'shift_end_time', 'shift_start_time' ))) from `shifts`' at line 1 (SQL: select SELECT time(sum(TIMEDIFF( 'shift_end_time', 'shift_start_time' ))) from `shifts` where `time_sheet_id` = 35)
You have a sintax error probably because you don't have to write the SELECT keyword in the selectRaw function ( the keyword is added implicity by the query builder in this case ):
->selectRaw("time(sum(TIMEDIFF( 'shift_end_time', 'shift_start_time' )))")

[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

getting exception with SQLKorma for syntax: Failure to execute query with SQL

Any idea what is this exception trying to convey ?
I am using sqlKorma with Postgres 9.3.
I am trying to insert multiple rows at once in a table and I am getting a syntax error.
Now neither do I have a "0" anywhere in my query nor am I writing raw SQL to be messing up the syntax.
the korma docs are also not very clear.
Failure to execute query with SQL:
DO 0 :: []
PSQLException:
Message: ERROR: syntax error at or near "0"
Position: 4
SQLState: 42601
Error Code: 0
org.postgresql.util.PSQLException: ERROR: syntax error at or near "0"
Position: 4
Thats my code
(insert vendor-subsidiary-allowance
(values (vec (for [p (seq percentages)]
{:id (java.util.UUID/randomUUID)
:type "%"
:id_allowance_category (utils.uuid/from-str (p 0))
:id_vendor_subsidiary (allowance-form "vendor_sub_id")
:value (parse-number (p 1))}))))
NOTE: percentages is a dictionary with uuid strings as keys and value as some numeric string
Perhaps you want to read this to find the way to print the generated SQL to console.
You can use sql-only or dry-run macro to do this.
Print the generated SQL with sql-only or dry-run and check that the SQL is okay.

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