Ignited Datatables selecting all columns even when column names are specified - php

I can't seem to get this working and it's driving me nuts.
I'm using CodeIgniter's Ignited Datatables library I found on github
I have the below method for getting records from a table joined to another:
public function get_templates_ajax() {
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
$this->datatables->from('templates tem');
$this->datatables->join('items itm', 'tem.template_id = itm.template_id', 'left');
$this->datatables->where('tem.user_id', $this->session->user_id);
$this->datatables->group_by('tem.template_id');
$this->datatables->add_column('actions', 'EditDelete', 'tem.template_id, tem.name, tem.vat');
return $this->datatables->generate();
}
Yes, I have a field named user_id in both tables, but I'm not selecting the column, however, I get this error: Duplicate column name 'user_id'.
I specified the columns I want selected as seen below:
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
I know if I wanted to select the user_id column, I'd use an alias, but I'm not selecting it.
Doing $this->db->last_query(); dumped this SQL:
SELECT COUNT(*) FROM (SELECT * FROM `templates` `tem` LEFT JOIN `items` `itm` ON `tem`.`template_id` = `itm`.`template_id` WHERE `tem`.`user_id` = '1' GROUP BY `tem`.`template_id`) SqueryAux
So it seems that the select method is being ignored while it is selecting all columns from both tables.
What could I be doing wrong?

After much digging, I solved the problem by making some adjustments to the library.
Apparently, the problem was originating from the get_total_results(); method in the class, more specifically these 2 line:
$subquery = $this->ci->db->get_compiled_select($this->table);
$countingsql = "SELECT COUNT(*) FROM (" . $subquery . ") SqueryAux";
The subquery variable was selecting all columns from the main table and joined tables using dear old *.
Here is what I did to fix the problem:
I replaced the $subquery line with this:
....
//ensure table with alias does not contain more than 1 space between original table name and alias
$this->table = preg_replace('!\s+!', ' ', $this->table);
$tbl = explode(" ", $this->table);
//if table has alias, get it, else get table name
$table = count($tbl) > 1 ? $tbl[1] : $tbl[0];
$subquery = $this->ci->db->get_compiled_select($this->table);
//prefix table/alias to * so it selects columns from the main table only
$subquery = str_replace("*", "{$table}.*", $subquery);
....
Hope it helps someone.

Related

Codeigniter Join tables from 2 databases

Is it possible to join 2 tables from different database?
Here is my query
public function getschedule($section){
$this->dbsections->select('*');
$this->dbsections->from($section);
//I want to join the column "teacher" of the "section_name" table that is in the "dbsections" database
//to the "id" column of the "teachers" table in the "dbusers" database
$this->dbsections->join('teachers', 'teachers.ID = '.$section.'.TEACHER');
$query = $this->dbsections->get();
$query = $this->dbsections->get();
return $query->result_array();
}
This code gives me error, obviously. I also tried
$this->dbsections->join('dbusers.teachers', 'teachers.ID = '.$section.'.TEACHER');
and
$this->dbsections->join('dbusers.teachers', 'teachers.ID = dbsections.'.$section.'.TEACHER');
But both gives me error
Error Number: 1096
No tables used
SELECT *
You need table name in select * as
$this->dbsections->select("$section.*");// write tour table name before *
And Remove one time
// $query = $this->dbsections->get();

error on array retrieved from JOIN query on two tables

hope my title is clear. I am trying to retrieve results from two tables.
So I want everything (hence *) from the table called 'albums'.
and I want only all matching (with album_id) results from table 'contributors'.
$result = mysql_query("SELECT * FROM albums LEFT JOIN contributors ON albums.album_id =
contributors.album_id ORDER BY albums.datum DESC; ") or die(mysql_error());
$aantal_rijen = mysql_num_rows($result);
if ($aantal_rijen > 0) {
for ($i = 0; $i < $aantal_rijen; $i++){
$contributors[] = mysql_result($result, $i, 'contributors');}
but i get a list of similar errors:
contributor not found in MySQL result index ...
Joining of two tables is totally new to my, and maybe it's not the way to go, but maybe it's just a plain simple error in this code, anyway, I'm stuck here,
all help is welcome
thx S
http://php.net/manual/en/function.mysql-result.php
FIELD
The name or offset of the field being retrieved.
It can be the field's offset, the field's name, or the field's table dot field
name (tablename.fieldname). If the column name has
been aliased ('select foo as bar from...'), use the alias instead of
the column name. If undefined, the first field is retrieved.
You're just using the table name contributors, so either you need to specify a single field or limit your select to only the fields you want
$contributors[] = mysql_result($result, $i, 'contributors.name');
OR
$result = mysql_query("
SELECT contributors.*
FROM albums
LEFT JOIN contributors ON albums.album_id = contributors.album_id
ORDER BY albums.datum DESC;
") or die(mysql_error());

Codeigniter active record left join issue

I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns

Codeigniter joining tables?

I have this structure of the tables:
Table Name: collisions
Fields: id, creator1, creator2
(1, 1, 2) - simple data in my sql table
Table Name: creators
Fields: id, artistname
(1, john smith)- simple data in my sql table
(2, steven michael)- simple data in my sql table
What i need is to join these tables so i can get the artist name instead of creator1 id and creator 2 id.
This is what I have done so far:
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = cr1.id AND collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
but I am getting this error:
Unknown column 'cr1.id' in 'on clause'
SELECT `collisions`.*, `creators`.`artist_name` AS cr1, `creators`.`artist_name` as cr2 FROM (`collisions`) LEFT JOIN `creators` ON `collisions`.`creator1` = `cr1`.`id` AND collisions.creator2 = cr2.id
Can someone tell me what I am doing wrong?
This did the job
$this->db->select('collisions.*, cr1.artist_name as cr1, cr2.artist_name as cr2');
$this->db->join('creators AS cr1', 'collisions.creator1 = cr1.id', 'left');
$this->db->join('creators AS cr2', 'collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
Please use actual table name instead of alias :
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = creators.id AND collisions.creator2 = creators.id', 'left');
$data = $this->db->get('collisions')->result();
the reason why you cant use alias is that the execution of sql is in the following order:
1)FROM clause
2)WHERE clause
3)GROUP BY clause
4)HAVING clause
5)SELECT clause
6)ORDER BY clause
since you were using alias which is created in select clause which executes after where clause.
That's why you can not use the alias that which does not exits.

Copy one table to another with different colum count

As i am far from an expert in php this got me stunned and i can't seem to make a script for it.
Lets see if i can explain this as clearly as possible.
Lets say i have table1 and table2
Table1 = (teamid, name, round1pos, round1score, round2pos, round2score)
Table2 = (id, tournamentid, teamid, name, round1pos, round1score, round2pos, round2score...till round10pos/round10score)
When copied from table1 to table 2 i want to add 2 fields in front of it. (id and tournamentid)
The problem i am facing is that Table1 has a different amount of roundxpos/roundxscore each time.
Basically what i want to do is once a tournament is over i want to delete the table. but copy the data inside it to another table to archive the results. but each tournament can have a different size of rounds.
I hope someone can understand what i am trying to achieve +_+.
You should create a third table, remove the roundX columns from your existing tables and reference them with their IDs.
rounds: team_id, tournament_id, no, pos, score
You should normalize your tables but in the meantime....
I'm assuming the main problem is handling the variable number of roundxpos and roundxscore columns in the code.
Hope this helps:
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%pos'
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%score'
Create the table2 inserts by looping through field names
//example, assuming results are fetched into an associative array
$query = "INSERT INTO table2 (tournamentid, teamid, name)";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= "( SELECT $tournamentid, '' teamid, name";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= ")";

Categories