combine columns into one column mysql - php

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

Related

CodeIgniter Query Escaping Quotes

I have the following simple query which works perfectly in MySQL;
select * from client_contact
where date_format(client_next_contact_on, '%Y-%m-%d') = '2018-07-25'
I've then added this in my codeigniter query but the error I get is;
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 ''2018-07-25'' at line 3
SELECT * FROM (client_contact) WHERE
dateformat(client_next_contact_on, '%Y-%m-%d') '2018-07-25'
By the looks of the above, it's missing the = in the query.
Here's my query in codeigniter;
$today = new DateTime();
$today_formatted = $today->format('Y-m-d');
$this->db->where('dateformat(client_next_contact_on, \'%Y-%m-%d\')', $today_formatted);
$return = $this->db->get('client_contact')->row_array();
If you're wondering why I need to use date_format, it's because it's stored as a date time in my database for other purposes. For this purpose, I need a list of clients that I need to contact today, regardless of the time.
Just include the equals in the where statement, and rename dateformat as it isn't a function in MySQL. Use DATE_FORMAT:
$this->db->where('DATE_FORMAT(client_next_contact_on, \'%Y-%m-%d\') =', $today_formatted);
Now, onto the guts of why code igniter chose not to include an equals sign, which (by the documentation, it should have). On this line of the codeigniter source, it calls this function to determine if it contains an operator. Apparently because you put a space after the , it believed you included an operator, so a simple manual adjustment to add this in is fine.
protected function _has_operator($str)
{
return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
}
You can see where the regex matched here: https://regex101.com/r/BTuZxj/1

count of items from another table for each row in table

I have a list of user-profiles when I have this query. I want to retrieve nr of followers for each (every) user, but I only get one row result from query (there are a lot of users)
$this->db->select('up.name, up.id, up.image, up.name_id, up.created, COUNT(followers.user_id) as followed_by_count');
$this->db->join('user_profiles up', 'u.id = up.user_id', 'left');
$this->db->join('followers', 'up.user_id = followers.user_id', 'left');
//Something like this? (It doesn't work)
//$this->db->group_by('COUNT(followers.user_id) as followed_by_count');
//When tried this I get:
//"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 followed_by_count"
$this->db->order_by('up.created', 'DESC');
I guess I should use group by in some way? The query works when not using followers-table. It also works when not using group_by but I obviously don't get the count(s) I want then.
Change
$this->db->group_by('COUNT(followers.user_id) as followed_by_count');
To
$this->db->group_by('u.id');
Note : This code given as per your given code and assume that your code is syntactically right.

Codeigniter $this->db->select() not work with Round(Max()) or FORMAT(MAX())

I write following code
$this->db->select('SUM(qty) as total_qty,(FORMAT(SUM(amount),2)) as total_amount');
$this->db->where('Invoice_Rec_No',$Invoice_Rec_No);
$result=$this->db->get($this->invoice_products_tbl);
$total_data=$result->row();
but getting error
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 (tbl_invoice_products) WHERE Invoice_Rec_No = 7' at line 2
SELECT SUM(qty) as total_qty, (FORMAT(SUM(amount), 2)) as total_amount FROM (tbl_invoice_products) WHERE Invoice_Rec_No = 7
Filename: C:\wamp\www\admin_followme247_master\system\database\DB_driver.php
I want to execute this query with codeigniter ActiveRecord.
User second parameter FALSE in db select method
$this->db->select('SUM(qty) as total_qty,
(FORMAT(SUM(amount),2)) as total_amount', FALSE);
CI db class is automatic add (apostrophe) when manipulate sql query, if you pass send parameterFALSEinselect` method then it is keep same as input.
You can format your code like this
$select = array(
'SUM(qty) as total_qty',
'(FORMAT(SUM(amount),2)) as total_amount'
);
$this->db->select($select);
$this->db->where('Invoice_Rec_No',$Invoice_Rec_No);
$result=$this->db->get($this->invoice_products_tbl);
$total_data=$result->row();
For simple column selection it is fine to use string but for complex selection like this one you can either use an array or select each column separately

MySQL query into Code Igniter Active Directory format?

I'm trying to get mysql query into Code Igniter's Active Record syntax but am having a bit of a hard time.
The query is as a result of this question: Multiple mysql ORDER BY's for multidimensional ordering/grouping
I've attempted to format the query myself, have tackled a couple of errors, but am unsure how to progress. I had to add in the get_compiled_select() function to DB_active_rec.php myself and change the _reset_select() from protected to public to get it to run at all.
The suggested query is:
select
t.id,
t.group,
t.date,
t.comlete
from
YourTable t
left join
(select
m.group,
min(m.date) as mindate,
min(t.complete) as groupcomplete
from
YourTable m) mt on mt.group = t.group
order by
coalesce(mt.groupcomplete, t.complete),
coalesce(mt.mindate, t.date),
t.group,
t.complete,
t.date
My translation looks like this (note that there's a 'where' clause not in the original, and that 'date' is actually 'due'):
// Sub query
$this->db->select('m.group, min(m.due) as mindate, min(t.complete) as groupcomplete');
$this->db->from('task m');
$this->db->where('property', $property);
$subquery = $this->db->get_compiled_select();
$this->db->_reset_select();
// Main query
$this->db->select('*');
$this->db->where('property', $property);
$this->db->from('task t');
$this->db->join('($subquery) mt','mt.group = t.group');
$this->db->order_by('coalesce(mt.groupcomplete, t.complete)');
$this->db->order_by('coalesce(mt.mindate, t.due)');
$this->db->order_by('t.group');
$this->db->order_by('t.complete');
$this->db->order_by('t.due');
$query = $this -> db -> get();
// Return
return $query->result();
Unfortunately this is just throwing an 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 'mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.gr' at line 3
The query as reported by CI looks like:
SELECT * FROM (`task` t) JOIN ($subquery) mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.groupcomplete, `t`.`complete)`, coalesce(mt.mindate, `t`.`date)`, `t`.`due`, `t`.`complete`, `t`.`date`
Anyone able to lend some advice as to how to get this formatted correctly? My mysql skills are, unfortunately, pretty bare, so this is pushing my abilities. Much of the approach of my translation is from answers on Stack Overflow, as I have no experience combining queries in this way (with the subquery).
The problem (or 'one of the problems') is here:
$this->db->join('($subquery) mt','mt.group = t.group');
You use single quotes, so the variable $subquery doesn't get expanded.
This can also be seen in the query that is outputted by CodeIgniter.
When you have multiple order by statements u separate them by comma like this
$this->db->order_by('coalesce(mt.groupcomplete, t.complete), coalesce(mt.mindate, t.date), t.due, t.complete, t.date');

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