Error with Find query in cakephp - php

CakePHP Code
$data = $this->DropDownMultiple->find('all',array(
'conditions'=>array('FIND_IN_SET(?,DropDownMultiple.interest)' => array('football')),
'order'=>'created_on desc'
)
);
SQL Query
SELECT DropDownMultiple.*
FROM `cakephp_tutorial`.`drop_down_multiples` AS `DropDownMultiple`
WHERE FIND_IN_SET('football',`DropDownMultiple`.`interest`) =
ORDER BY `created_on` DESC
Syntax Error
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 'ORDER BY created_on desc' at line 1
Problem is insert = sign at the end of where condition. Why this happen? Where am I wrong? help me.

Why don't you use the code that I've posted in the comments of the original questions answer?
You seem to have managed to remove the hidden chars that I've mentioned, at least they are not present in the code you are showing here anymore, not sure about the code that you are actually using though.
However, you are not using the format that I've shown you:
$data = $this->DropDownMultiple->find('all', array(
'conditions' => array(
'FIND_IN_SET(?, `DropDownMultiple`.`interest`)' => 'football'
),
'order' => 'created_on desc'
)
);
Note the quotes around the model and field name, and most important, the space after the ,.
Requiring that space might be a bug in CakePHP, not sure.
Also note that there's no need to wrap the value into an array, even though it works in case it contains only a single entry.

Related

PHP SQL get unique values from column

I want to create to modify sql query so it will choose all unique values (it's integer) from column traffic_type. There is a part of code that should be edited:
$statistic_query = array(
'select' => array(
'SUM(installs) AS installs_count',
'SUM(fake_installs) AS fake_installs_count',
'SUM(searchs) AS searchs_count',
'SUM(clicks) AS clicks_count',
'AVG(bid) AS bid_avg',
'SUM(user_profit) AS user_profit_sum',
'SUM(system_profit) AS system_profit_sum',
'SUM(visits) AS visits_count',
'SUM(downloads) AS downloads_count',
'SUM(DISTINCT traffic_type) AS traffic_type_count'
),
'from' => ' statistic'
);
It's working but I don't need to sum unique values I want to get all unique values separated with commas like 0, 2. When I'm changing 'SUM(DISTINCT traffic_type) AS traffic_type_count' to 'DISTINCT traffic_type AS traffic_type_count' - there is an error:
Error 500
CDbCommand failed to execute the SQL statement: 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 'DISTINCT traffic_type) AS traffic_type_count, `dt_add` FROM `statistic` WHERE (d' at line 1
It can be because it gets an array, not number. So is there a way to get all unique values separated with commas like one variable, not an array?
When you want to get comma separated list of values use GROUP_CONCAT
GROUP_CONCAT(traffic_type) AS traffic_type_count
Also you can use DISTINCT within for filter only unique values
GROUP_CONCAT(DISTINCT traffic_type) AS traffic_type_count
online SQL editor

CakePHP 3 find() with order foreach each row

Man, I don’t know why this isn’t working, i’m following the Manuel verbatim.
I have a ProductStyles Table that has an order column. Suppose i have 5 rows. And I delete number 3. I want to find all rows matching the product id and iterate through each one of them replacing the order # incrementially.
Productstyle Table
id - product_id - order
My first step is to just fetch all the rows matching product ID in order so i can do a foreach but I keep get SQL errors. Honestly I don’t know SQL that well other than the basic select.
$query = $this->ProductStyles->find()
->where(['product_id'=> 1 ])
->order(['order' => 'ASC'])
;
//debug($query);
//debug( $query->all() ); //this throws an error
Error Message:
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 'order ASC' at line 1
SQL:
//SELECT ProductStyles.id AS `ProductStyles__id`, //ProductStyles.product_id AS
//`ProductStyles__product_id`, ProductStyles.style_id AS //`ProductStyles__style_id`,
//ProductStyles.order AS `ProductStyles__order` FROM product_styles ProductStyles
//WHERE product_id = :c0 ORDER BY order ASC
//die;
$i = 1;
foreach ($query as $row) {
//debug($row); die;
$ps= $this->ProductStyles->get($row->id);
//debug($ps);die;
$ps->order = $i;
$this->ProductStyles->patchEntity($ps,['order'=> $i]);
$this->ProductStyles->save($ps);
$i++;
}
order is a reservered word, and is not allowed to be used in an unquoted (in this case non-backticked) fashion, it would need to be used in the form of `order`
See
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
I would suggest to change the column name, that's the easiest, and non-performance affecting fix. Another option would be to enable automatic identifier quoting, this will however affect the performance, and cannot be applied everywhere, see
Cookbook > Database Access & ORM > Database Basics > Identifier Quoting
order is a reserved keyword in SQL, so, if you want to use as a column name, you need to use quotes, like this:
SELECT * FROM table ORDER BY `order` ASC
As you can see in the error, is not being quoted.
Maybe you have to use $this->Model->query() and write the query manually.
Another solution is change the "order" column to another name.
Hope this helps.

CAKEphp Virtual field not working

Because i have two price columns in my table (subscription_discount and subscription_price). I need to find a way to find the lowest of the two and use it. The problem is that this only has to occur when subscription_discount is lower then subscription_price and when subscription_discount is not 0.00.
This is my code to create the virtual field in my model:
public $virtualFields = array(
'end_price' => "IF(Abonnement.subscription_discount IS NOT NULL OR Abonnement.subscription_discount < Abonnement.subscription_price, Abonnement.subscription_price), Abonnement.subscription_discount)"
);
Somehow this ends up in an error in my view:
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 '),
Abonnement.subscription_discount)) AS Abonnement__end_price FROM
`cake' at line 1
I don't understand what is going wrong here.
public $virtualFields = array(
'end_price' => "IF(Abonnement.subscription_discount IS NOT NULL OR Abonnement.subscription_discount < Abonnement.subscription_price, Abonnement.subscription_price>>>**)**<<<, Abonnement.subscription_discount)"
);
remove it

combine columns into one column mysql

I would like to combine two columns in one column as Fullname, and for that I have written the following code:
$this->db->select('CONCAT(first_name," ",last_name) AS FullName');
$this->db->from('customer');
$this->db->where('user_id',1);
$query = $this->db->get();
return $query->result_array();
The resulting query would be:
SELECT CONCAT(first_name," ",last_name) AS FullName
FROM customer
WHERE user_id = 1
but when i execute the above code it gives me:
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 'FROM (customer) WHERE user_id = '1' at line 2
I have also tried with concat_ws group_concat but not able to get it work. Can anyone see what I'm doing wrong?
By default, CI tries to escape what you pass to db->select() (in case you were passing in user-generated values). You can disable this feature by passing false as a second argument.
$this->db->select('CONCAT(first_name," ",last_name) AS FullName', false);
I have been through this before with CI, in my case CI was wrongly creating the query, for example putting simgle quotes where they shouldn't be.
My advice create the query yourself and run it, you could be surprise :P

CodeIgniter inserting apostrophes in to database query

I have a bit of a strange problem that has been baffling me. All I am trying to do is run a query on a database table but for some reason, CodeIgniter is putting apostrophes into the query which is subsequently breaking the page.
My code looks like this:
$this->db->select("SUBSTRING(body,5)");
$this->db->order_by("date", "desc");
$this->data['query'] = $this->db->get_where('blog-entries', array('status' => 'P'), 3);
But I get an error on this page:
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 'FROM (`blog-entries`) WHERE `status` = 'P' ORDER BY `date` desc LIMIT 3' at line 2
The query is actually being run as:
SELECT SUBSTRING(body, `5)` FROM (`blog-entries`) WHERE `status` = 'P' ORDER BY `date` desc LIMIT 3
As you can see for some reason apostrophes have been added around the number 5 within the substring. If I remove the substring then everything works and if I remove the apostrophes and run the query directly on my db it also works.
Has any got any ideas as to why this may be happening or have a solution?
Your help would be greatly appreciated.
Many thanks,
G.
Use this:
$this->db->select("SUBSTRING(body,5)", FALSE);
As a default, Codeigniter tries to add back-ticks where it thinks is relevant. Sometimes it adds them where it shouldn't. Passing FALSE as the second parameter prevents it from doing this.

Categories