How to query a 2 table database in Codeigniter - php

I have 2 tables in a single database.
For example:
Table 1 Columns:
id | code | name
Table 2 Columns:
id | code | family | etc.
How can I query both tables based on the overlapping code column to retrieve family column?
This is what I currently have:
$query = $this->db
->select('*')
->from('table 1')
->where('code', '123');
$query->get()->result();
The above query will retrieve the row(s) with code 123 but I'd like to get the corresponding family data from table 2. How can I do this?

Use join(). Something like:
$query = $this->db
->select('*')
->from('table1')
->join('table2', 'table1.code = table2.code')
->where('code', '123');
Docs on the function are here: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

well you must add a sentence Join, it will let you query two tables.
$dataquery = array('table1.code' => '123'); //var in order to where
$this->db->select('table1.id As id1, table2.id As id2') //separate the ids with names
$this->db->join('table2.code','tabla1.code'); //code is overlapping
$query = $this->db->get_where('table1',$dataquery);
return $query->get()->result_array();//Return array if you want
Cheers!

Related

MYSQL: List all column names where their values = "Yes"

I have a table like so:
User_Id Column1 Column2 Column3
1 Yes No Yes
2
I want to use mysql query to list all the column names (there are more than 3) which match the User_Id '1' and have a value of 'Yes'.
I get an error:
Trying to get property 'num_rows' of non-object
Here is what I have tried:
<?php $myStats = $mysqli->query("SELECT COLUMN_NAME FROM user_services.columns WHERE myColumn = 'Yes'");
if ($myStats->num_rows > 0) {
// output data of each row
while($row = $myStats->fetch_assoc()) {
$rows[] = $row; }
return $rows; ?>
Please can someone show me where I am going wrong?
Thanks in advance.
The CONCAT_WS function comes in handy here:
SELECT CONCAT_WS(',', IF(Column1='Yes', 'Column1', NULL),
IF(Column2='Yes', 'Column2', NULL),
IF(Column3='Yes', 'Column3', NULL)) AS columns
FROM user_services.columns
WHERE User_Id = 1;
If you have more than 3 columns, then you may add more terms to above CONCAT_WS call. Your problem mainly seems to be a SQL one, so I won't add any PHP code.
Note that your design might be better off if your column strings were spread across rows, rather than columns. For instance, consider the following alternative:
User_Id | number | val
1 | 1 | Yes
1 | 2 | No
1 | 3 | Yes
Then, if you wanted all column numbers which were yes for user 1, you could simply do:
SELECT
User_Id,
GROUP_CONCAT(number ORDER BY number) columns
FROM yourTable
WHERE
User_Id = 1
GROUP BY
User_Id;

Joining multiple tables returning 0 for specific column? PHP/MySQL

I'm having a problem at the moment where I have a column called rating in the links table and there is definitely values other than 0 within the column but 0 is the only value which is returned foreach link. When I do a simple get for that column it then shows all the other values but not when I do an SQL Join.
I know the problem is my joining of the tables but I'm unsure how I would go about joining these specific tables.
Database Table Structure
The rating column is the one which is causing me problems.
'links' id | title | url | user_id | list_id | rating | weight | date_created
'list' id | list_title | list_description | user_id | rating | views | date_created
'link_ratings' id | user_id | link_id | rated | date_created
Model:
public function get_latest(){
$this->db->limit(100);
$this->db->order_by('links.date_created', 'DESC');
$this->db->select('*');
$this->db->select('links.id as current_link_id');
$this->db->from('links');
$this->db->join('list', 'links.list_id = list.id');
$this->db->join('users', 'links.user_id = users.id');
$this->db->join('link_ratings', 'links.id = link_ratings.link_id','left');
$get_latest = $this->db->get();
return $get_latest;
}
Any Help is appreciated.
You should try this:
function get_latest(){
$this->db->select('list.*, users.*, links.id as current_link_id');
$this->db->from('links');
$this->db->join('list', 'links.list_id = list.id');
$this->db->join('users', 'links.user_id = users.id');
$this->db->join('link_ratings', 'links.id = link_ratings.link_id','left');
$this->db->order_by('links.date_created', 'DESC');
$this->db->limit(100);
$get_latest = $this->db->get()->result_array(); #fetch all rows here
echo "<pre>";print_r( $get_latest );die; #print all rows and see if its fetching ratings corrctly or not.
echo $this->db->last_query();die; #check the query generated
return $get_latest;
}
The reason will be purely logical, in that the join will be causing no results to be returned because there are no results. I've fallen into this many times.
I am not able to diagnose your particular problem but when faced with issues like this I:
1- turn on the CI profiler
2- var_dump the array so you can see what's going on
3- write a traditional SQL query and run it in PHPMyAdmin
One, or a combination of all three, will enable you to diagnose.

Joining tables by specific column using Doctrine

I am trying to get a single record for one table by checking for a variable that is in two associated tables.
For instance my tables are
user:
id | name
3781 | Foo Manchu
user_programs:
id | user_id | page_id
4150 | 3781 | 16974
Page
id | title | section_id
16974 | Dudes | 3
So I need to query and return the Users who have a section_id of 3
Users are associated to the user_program table which are assocaited to specific pages through page_id.
This is what I have which is not returning anything:
if($section_id == 3) {
$q = $this->createQuery('u');
$q->leftJoin('u.user_programs up');
$q->leftJoin('up.Page p');
$q->where('u.published=1 AND u.is_preview = 0 AND u.featured=1 AND fp.deleted_at IS NULL');
$q->addWhere('p.section_id=?', $section_id);
$q->orderBy('RAND()')->limit(1);
I can succesfully return the u query without doing the join, but I need to limit the query to only return users with a section_id on the associated page of 3.
If the schema is correct, then a User should have a Pages (or something like that) relation. You can write the query like this:
$query = $this->createQuery('u')
->innerJoin('u.Pages p')
->andWhere('u.published = ?', 1)
->andWhere('u.is_preview = ?', 0)
->andWhere('u.featured = ?', 1)
->addWhere('p.section_id = ?', $section_id)
->limit(1)
;
I removed the fp.deleted_at part as it makes no sense when using SoftDelete (I presume you use that) and the fp alias was not in the original query anyway.

Count Relational Table Rows

I'm trying to count the number of rows in a relational table many to many, but always returns the wrong value. When it is 1, always returns 2.
PS: All models and foreign keys in mysql are configured correctly.
Comments Table:
id | name
10 Comment Test
Users Table:
id | name
20 User Test
Likes (Comment/User) Many to Many:
user_id | comment_id
20 10
Code:
$criteria = new CDbCriteria;
$criteria->select='*, COUNT(likes.id) AS count_likes'; // I believe the error is in the use of COUNT (likes.id).
$criteria->with=array('likes'=>array('on'=>'user_id=20'));
$model = Comments::model()->findByPk($_GET['id'], $criteria);
// Return Wrong Value
echo $model->count_likes; // Return 2 where should be 1. (I need to use this case)
echo count($model->likes); // Return right value 1.
You should use Statistical Query, e.g. :
In your Comments model :
public function relations()
{
return array(
// ...
// I assume your relation table's name is "likes"
'likes'=>array(self::MANY_MANY, 'Users', 'likes(comment_id, user_id)'),
'likesCount'=>array(self::STAT, 'Users', 'likes(comment_id, user_id)'),
// ...
);
}
Are you planning on selecting from the LIKES table and group by them by their userid and comment id?
If so, you can use GROUP BY
Please take a look at the SQLFiddle here
http://sqlfiddle.com/#!2/bc29b8/1/0
SELECT uid, cid, COUNT(likes.cid) FROM likes GROUP BY uid, cid

Data from two tables and joining in codeigniter

I have two tables with following costruction:
errortype:
| id | errortype_text |
errorreason:
| id | errorreason_text | errortype_id |
I would like to select all data from errorreason table and replace the errortype_id data with the coresponding errortype_text.
How is this possible?
if the tables have a foreign key you can do that in your model:
$this->db->select('erroreason_text');
$this->db->join('errorreason', 'errortype.id = errorreason.id');
$query = $this->db->get('errortype');
return $query->result();
If you are talking about SQL/MySQL it should be:
SELECT `errortype_text`, `errorreason_text`, `errortype_id` FROM `errorreason` JOIN `errortype` ON `errortype`.`id`=`errorreason`.`id`
This joins your tables based on entries having the same id and it is exactly the method Yan suggested.
If you are explicitely referring to PHP/Codeigniter, you have to pass this as a parameter to mysql_query to be afterwards evaluated:
$query=mysql_query("SELECT `errortype_text`, `errorreason_text`, `errortype_id` FROM `errorreason` JOIN `errortype` ON `errortype`.`id`=`errorreason`.`id`");

Categories