count of items from another table for each row in table - php

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.

Related

How to Translate Codeigniter Pre Formatted Query Into an Original Mysql Query (e.g $this->db->select('table1.*,table2.*,table3.*'))

I have a website which is using a CodeIgniter framework and almost using CodeIgniter's preformatted query class in every request to process data from database built by my ex coworker.
One of the example is like this:
function tampilkan_data(){
$this->db->select('barang.*,barang_keluar.*,barang_masuk.*');
$this->db->from('barang');
$this->db->join('barang_keluar', 'barang.id_barang=barang_keluar.id_barang','left');
$this->db->join('barang_masuk', 'barang.id_barang=barang_masuk.id_barang','left');
$this->db->order_by('barang.id_barang','asc');
$this->db->order_by('barang.kode_barang','asc');
$this->db->where('barang.status','0');
return $query = $this->db->get()->result();
}
I want to change the result from that query, but in order to understand it first I have to translate it into an original MySQL query. Attempted to do this:
SELECT `barang`.*, `barang_keluar`.*, `barang_masuk`.*
FROM `barang` AS A
LEFT JOIN `barang_keluar` AS B ON A.id_barang = B.id_barang
LEFT JOIN `barang_masuk` AS C ON A.id_barang = C.id_barang
ORDER BY A.id_barang ASC, A.kode_barang ASC
WHERE A.status = 0
But I got this error
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 'WHERE A.status = 0 LIMIT 0, 25' at line 6
I tried to remove the WHERE A.status = 0 to see which is wrong from my code the I got this error
1051 - Unknown table 'barang'
I thought the problem is in the line SELECT barang.*, barang_keluar.*, barang_masuk.*, because I didn't really know how to write it in an MySQL original formatted.
I already searched for this topic and I even tried to write the query straight to the search bar but I didn't find the right approach according to my case.
Hope someone can help
You can simply print your query, Then you can see your query in original sql format.
function tampilkan_data(){
$this->db->select('barang.*,barang_keluar.*,barang_masuk.*');
$this->db->from('barang');
$this->db->join('barang_keluar', 'barang.id_barang=barang_keluar.id_barang','left');
$this->db->join('barang_masuk', 'barang.id_barang=barang_masuk.id_barang','left');
$this->db->order_by('barang.id_barang','asc');
$this->db->order_by('barang.kode_barang','asc');
$this->db->where('barang.status','0');
$query = $this->db->get()->result(); // notice that i have removed the return keyword
echo $this->db->last_query(); // This will print your query directly on the screen.
}
But the error which you are getting is -> You don't have a table named barang.
Make sure that the table exists.
Hope It Helps...
If you want to look at the query string generated by the CI Query builder then you can log this method $this->db->last_query() which will give the last SQL query as string executed by it.
Your query is almost ok. But you will have to change it on order by. Because u have used asc more than once, that is not supported by mysql as well. You need to modify your query like below
SELECT A.*, B.*, C.*
FROM barang AS A
LEFT JOIN barang_keluar AS B ON A.id_barang = B.id_barang
LEFT JOIN barang_masuk AS C ON A.id_barang = C.id_barang
WHERE A.status = 0 ORDER BY A.id_barang, A.kode_barang ASC
Now be confirm that you have table barang in your database and try again. If you face another sql problem just reply with your screenshot of code snippet here.

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

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

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