codeigniter select join twice from same table - php

I have 3 tables, where is the first one for user. In another two I have id_user, for product who created or activation who created. How I can show all data from these two tables with both username? I figure out how to join 2 tables, but third I have join twice and I don't know how. This is example for two tables:
$query=$this->db->select('*')
->from('activation')
->join('products','products.id_pro = activation.id_pro')
->order_by('id_key','DESC')
->get();
Table activation has column user_a with user id, and product has column user_p with user id. Sometimes is same user sometimes not. Any helps?

Heres how I do it using aliases. You can format it your way too.
$this->db->select('tb1.*,tb2.*,u.*');
$this->db->join('table1name tb1','tb1.id = u.tb1_id');
$this->db->join('table2name tb2','tb2.id = u.tb2_id');
$this->db->order_by('u.id_key','DESC');
$result = $this->db->get('User u')->result();
If you want to alter between left and right join just add 'left' or 'right' to the join function.
$this->db->join('table1name pr1','pr1.id = u.tb1_id','right');
$this->db->join('table2name tb2','tb2.id = u.tb2_id','right');
This would preference your user table.

Related

How to select values of one table based on values of another table in SQL, PHP

I have 5 tables:
user ( user id, user name, etc.. )
role ( role_id, role_name )
user_role ( user_id, roles_id )
form ( form_id, form_name, etc.. )
form_access ( form_id, role_id )
user contains all registered user data.
role contains all different types of roles.
user_role contains which user has which role (all assigned roles are stored)
form contains all form data.
form_access contains data like which user role has which form access(one form can be assigned to many user roles).
I wanted to write a SQL query in PHP to retrieve form name based on the user logged in and his role, e.g. if Admin logs in he should get all forms, if HR logs in he should get forms related to HR only.
I tried this query:
$query = "SELECT ur.role_id, f.form_name, f.form_desc
FROM user_role ur, froms f
WHERE users.id = '".$user."',
users.status ='A',
forms.form_id = form_access.form_id,
from_access.role_id = user_role.role_id,
user_role.role_id = '".$user."'";`
Some one help me out with the correct query?
Since you start from the user_id you'll want to select from user_role and JOIN form_access and form.
SELECT `form`.`form_name` AS `form_name`
FROM `user_role` AS `ur`
INNER JOIN `form_access` AS `fa` ON `fa`.`role_id` = `ur`.`role_id`
INNER JOIN `form` AS `f` ON `f`.`form_id` = `fa`.`form_id`
WHERE `ur`.`user_id` = '".$user."'
PS: Check the table and column names.
You have to use AND .
BUT this should be better with joins.
$query = "SELECT ur.role_id, f.form_name, f.form_desc
FROM from_access
INNER JOIN froms f ON forms.form_id = form_access.form_id
INNER JOIN user_role ur ON from_access.role_id = user_role.role_id
INNER JOIN users ON users.id = user_role.role_id
WHERE users.id = '".$user."'
AND users.status ='A' ";
Your query is entirely broken, the others may have provided you with solutions but I'm going to give you some advice.
You've written an entire query, tried it, and it failed. I write queries all day long but if I write a whole query in Notepad then execute it it's probably going to have some minor error in it somewhere too.
Start from the ground up. You're trying to get a list of forms the user has access to, so lets start with the forms_access table. So what's the most basic starting point? How about:
SELECT fa.role_id, fa.form_id
FROM forms_access fa
Ok, thats overly simplified but if that ran at least we know we're connected to the database.
So we can easily tell which form_ids each role has access to. Now we know our linking table to users is user_roles, so let's add that in:
SELECT ur.user_id, fa.form_id, fa.role_id
FROM forms_access fa
INNER JOIN user_roles ur ON fa.role_id = ur.role_id
So we've joined forms_access to user_roles on the foreign key role_id. Now we can see for every user_id, which role_id they have and which form_ids they can access.
So we're pretty much there, we just need the information from the forms table, so lets JOIN to that too:
SELECT ur.user_id, f.form_name, f.form_desc, fa.form_id, fa.role_id
FROM forms_access fa
INNER JOIN user_roles ur ON ur.role_id = fa.role_id
INNER JOIN forms f ON f.form_id = ur.form_id
Great! Now we have a list of each form_name/form_desc that each user_id can access.
Try the above step by step, if you skip to the end there could well be an error since I have not tested the code, and I don't know for sure that your table definitions match the question. If you do it step by step you only need to check the most recently added line to find the error.
I have just noticed in the question that you also need users.status = 'A', so in the same way as above you'll need to join to the users table on an appropriate foreign key, give it a go.
Now, once you've done all that you need to filter the results to a specific user_id - notice up till this point we haven't bothered with the WHERE clause.
Now don't go adding some variant of WHERE user_id = '$user' right away because then you've introduced 2 potential errors. Instead try adding WHERE user_id = 0 (or some known user_id). Does the query run and the results look correct? Great, now finally try adding in your php variable.

Php mysql query for data from two tables

i have two tables in my database. table A is USERS and table B is relations, and the following are their columns
USERS(username, avatar, specialty) and RELATIONS(username1, username2, reldir)
RELATIONS stores the relationship between users, that is if, username1 is following username2, reldir = F, and if they are both following each other, reldir=FB and vice versa, this part has worked very well but
i need to query these tables so that i return a list of users from USERS which for example user A doesnt follow but have the same specialty as A...
i tried this, but its not working well ...
$spec = the specialty of user A
SELECT a.username, a.avatar, a.specialty FROM users a, relations b WHERE a.username!=b.username2 AND (b.reldir!='F' OR b.reldir!='FB') AND a.speciality ='$spec'
the query to me seems logically correct but i could be wrong. i need help
You need to add some keys for your tables, because you have two different tables and they doesn't linked.
For example, table USERS:
id (as primary_key), username, avatar, specialty
Table RELATIONS:
user_id, username2, reldir
user_id - it is field "id" from table USERS (instead your "username1")
Then you will be able create a query like this:
SELECT a.*
FROM users a, relations b
WHERE a.id = b.users_id
AND (b.reldir != 'F' OR b.reldir != 'FB')
AND a.speciality = '$spec'
ps: if I understood your question in the right way)

Mysql join query retrieving profile images of users with ids from other table

I'm having trouble with a join query, my issue is as follows.
Table: battles
Fields: id,attacker_id,defender_id
Table: users
Fields: id,profile_image
I would like to do a query to retrieve a battle and get the profile images as well from the other table.
Is there a way to do this in a single or do I have to do more than one?
Thanks in advance.
I wanted to wait a while to see if you had any attempt or if you will answer my first question to know if I understood the problem. But maybe you don't have a starting point. Try something like:
SELECT
a.profile_image as attacker_profile_image,
d.profile_image as defender_profile_image
FROM
`battles` b
LEFT JOIN
`users` a
ON
b.`attacker_id` = a.`id`
LEFT JOIN
`users` d
ON
b.`defender_id` = d.`id`
the problem here is the fact that you need to join with the users table twice, so you will need to create aliases for the columns you plan to use
This query will fetch the two images only, you will need to add the extra fields

PHP Which Join Statement to use when trying to grab data from another table

I'm trying to figure out the best approach, more specifically which JOIN to use, with my current situation:
I have two tables (entries, users) in my database. I'm querying and displaying all my news entries on one of my pages. With each entry, I'm also posting the entry information such as date, time and the author (or user) who created the entry.
In my "entries" table, I'm only inputting the user's id (user_id) as the post's author. The "users" table has all the author's information, such as name, email, etc.
Which "JOIN" statement would be best for specifically querying the "entries" table to display all my entries but to also grab certain information from my "users" table just by matching the user_id from "entries" to user_id in "users"?
Simple join statment
SELECT e.*,u.* FROM entries e JOIN users u
ON e.user_id = u.user.id
LEFT INNER JOIN probably.
it will display all from entries, and if users is atached to entries will be dispplayed aswell, else the field will be null.

Mysql relationships and getting linked data

I have been doing this for a while now, via some php, first lets say we have two tables:
Users
user_id name email
Images
image_id user_id url
user_id and user_id from images table would be linked with a relationship.
Now what I would do is select the user by their Id, check if the user is found, if so then make another query to images table, and check for num rows and loop through the return, is there a function that I could use that would allow me to just select the user and all the images that are linked to the user without doing a joint query.
Thank you for any help
When you say "without doing a joint query" I think you mean "without doing two queries."
In fact, what you want is probably a LEFT JOIN. The idea is that you select users from the user table matching some ID, and LEFT JOIN the images table. The left join will give you null values if no images exist for the user. If you use a normal join, the fact that no matching records exist in the images table will result in no rows returned.
Here is an example:
SELECT u.name, u.email, i.url
FROM Users u
LEFT JOIN Images i ON (i.user_id = u.user_id)
WHERE u.id = #SpecificUserID;
Assuming the user id is found and there are some images for that user, you will get a result that looks like this:
name email url
----- ----- -----
John j#a.com abc.jpg
John j#a.com def.jpg
John j#a.com ghi.jpg
Now as you can see, the name and email values keep repeating. You get a unique image url for each row and the matching username and email.
If you only select one user at a time, this is simple to process in a loop. On the first iteration read all three values. On subsequent iterations just read the url, adding it to your list or array.
Here is a useful tutorial on joins: Understanding JOINs in MySQL and Other Relational Databases
This can be done in one query rather than two by using an inner join to get your result set.
$sql = "SELECT u.user_nid, i.url
FROM tbl_user u
INNER JOIN i.user_nid = u.user_nid
WHERE user_nid = ?"
With this query you will receive a list of the users images and if there are no images returned or the user does not exist, than you will have a row return of zero.
You'll have to use a join to retrieve data from multiple tables in a single query.
The foreign key relationships enforce constraints. Ex: You can't insert a record into Table A referring to a key in Table B without the record actually being in Table B.

Categories