mysql join same table with another table - php

I have a table name tbl_user
This table contain a column name db_responsibleid contain the id of the responsible of this person and this person is in this table also
example mohammad have db_uid=1 and samir have db_responsibleid=1 this mean that mohammad is responsible for samir
also i have another table name tbl_department the table user contain the id of the department on the column name db_udepartment
I try to have the name of the department and the name and the last name of the responsible where db_uid='$id'
$id will be getting from url
this is the query that i use
SELECT
user.db_uid,
user.db_fname,
user.db_lname,
user.db_username,
user.db_pass,
user.db_email,
user.db_phone,
user.db_jobtitle,
user.db_level,
user.db_isemployee,
user.db_responsibleid,
user.db_companyname,
user.db_udepartment,
tbl_department.db_department,
tbl_department.db_did,
parent.db_responsibleid,
parent.db_fname as pfname,
parent.db_lname as plname,
parent.db_uid
from tbl_user as user,tbl_department
join tbl_user as parent
on
user.db_responsibleid=parent.db_uid
where
user.db_udepartment=tbl_department.db_did
and
user.db_uid='$id'
But this query give me this error Unknown column 'user.db_responsibleid' in 'on clause'
How can i solve this problem and get all information with the name of the responsible and the name of the department ??

You can not mix implizit and explizit join.
If you decided to use join you have to do it everywhere:
from tbl_user as user
join tbl_department on user.db_udepartment=tbl_department.db_did
join tbl_user as parent
on
user.db_responsibleid=parent.db_uid
where
user.db_uid='$id'
Hint: use prepared Statements to prevent SQL-injection

Related

Create a select from 3 tables

I´m trying to create a select from 3 different tables.
I want to show the name of the student, his class and the date of register.
I have 3 tables "aluno" (student), "turma" (class) and "data..." (date).
The name of the student is on the first table named "aluno".
The class of the stundet is on the table named "turma".
The register on the class is on the table named "matricula".
My objetive is to show the name o f the stundent, the name of the class (designacao) and the date (data).
My function that does this sql command is doing a join, but i´m not sure if its ok..
I think the select is wrong.
function DBRead15()
$sql="SELECT aluno.nome as nome, matricula.*, turma.*
FROM matricula
LEFT JOIN aluno ON aluno.n_processo = matricula.n_processo";
$result=DBExecute($sql);
while($res=mysqli_fetch_assoc($result))
{
$data[]=$res;
}
return $data;
Looking to your tables
SELECT aluno.nome as nome, matricula.*, turma.*
FROM matricula
LEFT JOIN aluno ON aluno.n_processo = matricula.n_processo
LEFT JOIN turma ON matricula.turma = turma.idturma
You started doing the query partially, but can continue as follows:
SELECT aluno.nome as nome, turma.designacao, matricula.data
FROM aluno
LEFT JOIN turma ON aluno.n_processo = matricula.n_processo
LEFT JOIN matricula ON turma.idturma = matricula.turma
This query assigns the connection between aluno and turma as aluno_id (one-to-many relationship) and the connection between turma and matricula as turma_id (one-to-many relationship). This query may not work perfectly for you, you will have to change aluno_id to whatever column connects your students to their classes.
This query is an example of how table JOIN in SQL.

Accessing Row from Mysql DB by chaining query of foreign key from another table

I'm having difficulty trying to find the best way to get my results from a table. I want to get the targeted row from a table by one using the primary key from another using a foreign key.
The tables are would be set similar to this(minus a lot of other attributes for space):
user Table:
user_Id(pk)
name
type
venue_Id(unique/indexed)
venue Table:
venue_Id(fk)
rating
Logic flow is: user_Id is provided by a session variable. Query DB table 'user' to find that user. Go to type of user to identify if user is person or venue. Assuming user is venue, go to DB table 'venue' and query table for rating using foreign key from unique/indexed venue_Id from user table.
The query looks like
SELECT rating FROM `venue` WHERE `user_Id` = '$user_Id' AND `type` = 'venue'
Is this possible, and if so, what is the correct way to go about it?
You have a few ways to retrieve this information.
Using JOIN:
SELECT v.rating
FROM venue v INNER JOIN user u
ON v.venue_id= u.venue_id
AND u.`user_Id` = '$user_Id' AND u.`type` = 'venue'
Using an IN sub-query
SELECT rating
FROM venue
WHERE venue_id IN (SELECT venue_id FROM user
WHERE `user_Id` = '$user_Id' AND `type` = 'venue')
BTW, you should consider protect your code from potential SQL Injections
Its a bit unclear you explained that way.
From what I get, there is 2 table User and Venue.
In User table u have: user_id, venue_id, name, type.
While in Venue table u have: venue_id, rating.
You are expecting to get rating (Venue Table) while you use the WHERE clause in user_id and type which both stored on User Table.
Your Query:
SELECT rating FROM venue WHERE user_Id = '$user_Id' AND type = 'venue'
It is impossible to get it done like above because you are selecting from venue table while user_id and type is not from venue table. So it will make it unidentified even you have chaining the FK. Because FK will only to show and make some constraint to parent child table.
The query should be something like this:
SELECT rating FROM venue v JOIN user u on v.venue_id = u.venue_id WHERE u.user_Id = '$user_Id' AND u.type = 'venue'
Correct me if I am wrong..
Combining rows from two tables based on the tables having columns with equal values is called an equi-join operation, it's the pattern we typically use to "follow" foreign key relationships.
As an example:
$sql = "SELECT v.rating
FROM `venue` v
JOIN `user` s
ON s.venue_Id = v.venue_Id
AND s.type` = 'venue'
WHERE s.user_Id` = '" . mysqli_real_escape_string($con, $user_Id) ."'"
This isn't the only pattern, there are several other query forms that will return an equivalent result.
As an example of using an EXISTS predicate:
$sql = "SELECT v.rating
FROM `venue` v
WHERE EXISTS
( SELECT 1
FROM `user` s
WHERE s.venue_Id = v.venue_Id
AND s.type` = 'venue'
AND s.user_Id` = '"
. mysqli_real_escape_string($con, $user_Id)
."'"
)";
The original query appears to be vulnerable to SQL Injection; the example queries demonstrate the use of the mysqli_real_escape_string function to "escape" unsafe values and make them safe to include in SQL text. (That function would only be appropriate if you are using the mysqli interface. Using prepared statements with bind placeholders is another approach.

Search data from multiple table

I have 2 table
Table-1 - user
user(ID.Name,Class)
Table-2 - Category
Category(ID,user_id,cat_id)
if user input a data from text field the how to search data from both table
Just query both tables and use the 'OR' operator for the columns you want to search in
SELECT * from user, category WHERE user.id=[text field] or category.user_id=[text field] or category.cat_id=[text field]
PHP Example: (assuming you are using MySQL database - you also need mysqli enabled in your php.ini file)
$mysqli = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
if (mysqli_connect_errno($mysqli)) {throw new exception("Failed to connect to MySQL: " . mysqli_connect_error());}
$sql = " SELECT * from user, category WHERE user.id='".$text_field."' or category.user_id='".$text_field."' or category.cat_id='".$text_field."'";
$rows = $result->fetch_array(MYSQLI_ASSOC);
foreach($rows as $row){
print_r($row);
}
This should get the records and show you the response from the array.
I hope you have added primary key & foreign key relations to these tables, in-order to grab data from both the tables you have two ways, either do multiplication of both table and bring in all the data else make use of JOIN that does the same in efficient way
Hoping to have your table schema as
USER [table] having id, username, name, password
CATEGORY [table] having id, name, description, user_id
So the query will become
SELECT U.*, C.id as cat_id, C.name as cat_name, C.description as cat_desc
FROM USER U
JOIN CATEGORY C ON C.user_id = U.id
If you have user inputting data from input fields, that becomes a filter query to be added in our above query, assume user is entering Name of category and wants the result set of the same then the above query gets added with WHERE clause as below
WHERE C.name LIKE '%{INPUT FIELD CONTENT HERE}%'
I have used LIKE clause above to allow us doing PARTIAL search
Hope this helps you

Turning user ID into name (separate tables) in PHP

I am currently trying to display the username of people who i am following, the problem is that during the following process, only the ID of me and the person i'm following is stored.
I've got it to the point where the ID's are displayed but i'd like to show the names hyperlinked. $p_id is the profile ID.
Here's what I've got:
$following = mysql_query("SELECT `follower`, `followed` FROM user_follow WHERE follower=$p_id");
I am following: <?php while($apple = mysql_fetch_array($following)){
echo '+'.$apple['followed'].' ';
}?>
The usernames are in a different table "users" under the field "username" - I need them to match up with the ID's that are currently displayed, and be displayed.
So what you need is a pair of JOINs (implicitly INNER JOIN) against users, one to join in the follower and one to join in the followed.
SELECT
/* Rather than SELECT * you need to be specific about the columns, and
give them aliases like followed_name since you have 2 tables with the same
column names in the query */
ufollower.id AS follower_id,
ufollower.username AS follower_name,
ufollowed.id AS followed_id,
ufollowed.username AS followed_name
FROM
/* JOIN twice against users, once to get the follower and once to get the followed */
user_follow
/* users aliased as ufollower to get the follower details */
JOIN users ufollower ON ufollower.id = user_follow.follower
/* users aliased as ufollowed to get the followed details */
JOIN users ufollowed ON ufollowed.id = user_follow.followed
WHERE
user_follow.follower = $p_id
In your loop, the names are available in follower_name, followed_name.
while($apple = mysql_fetch_array($following)){
// Be sure to wrap the name in htmlspecialchars() to encode characters that could break html.
// This has the followed id in the href and the followed name in the link text...
echo '+'.htmlspecialchars($apple['followed_name']) .' ';
}
You need to join them together - and because you want to output two id's names independently, you have to double-join the same table twice.
SELECT
uf.follower,
uf.username AS followerUsername,
uf.followed,
u2.username AS followedUsername
FROM
user_follow AS uf
INNER JOIN
users AS u1
ON
uf.follower = u1.userID
INNER JOIN
users AS u2
ON
uf.followed = u2.userID
WHERE
follower = ?
Please use prepared statements or escaping if you create SQL statements! A call to mysql_real_escape_string() saves you from SQL injection attacks.

How could I compare these database values in PHP?

So a user selects from a drop down list a value. I take this value, put it into a variable, then select from the database the ID value of that table A holding the selected value also.
So now I'm trying to use that ID value to get to a many-to-many relationship table that has the selected value from table A to a different table B. The many-to-many relationship table has both IDs. How can I compare this using PHP?
So it would be like:
$A = $_POST['a'];
$sql = "SELECT a, aID from TABLEA WHERE a = $A";
What do I do then to compare the aID with the many-to-many relationships table, then get the other ID in that table and then take that ID to get values from table B?
You can do this with a join in your SQL:
SELECT table_b.* FROM ab_association
LEFT JOIN table_b ON table_b.id = ab_association.b_id
WHERE ab_association.a_id = $specified_id;
That assumes that your many-to-many join table is called ab_association and has two columns, one called a_id that corresponds to table_a.id, and b_id that corresponds to table_b.id.
Update: I removed the table name aliases since they seem to be confusing you.
Another Update: In PHP, here's how you would do that (sans business logic):
<?
// connect to db here
$a_id = mysql_real_escape_string($_POST['a_id']);
$result = mysql_query("SELECT table_b.* FROM ab_association LEFT JOIN table_b ON table_b.id = ab_association.b_id WHERE ab_association.a_id = $a_id;");
// in your view/template
while(false !== (mysql_fetch_object($result))) {
// build your output for each row
}
?>
SELECT *
FROM table_a
LEFT JOIN ab_association ON table_a.aID = ab_association.aID
LEFT JOIN table_b ON table_b.bID = ab_association.bID
WHERE table_a.a = $A
Notes:
I used some underscores in tablenames, so table_a instead of TABLEA (just like Coreyward did) to distinguish between sql and names
You should specify the columns you need instead of 'SELECT *' if many columns aren't needed
You can use JOIN instead of LEFT JOIN if you want get an empty recordset when no match in the many-to-many is found. (Using a LEFT JOIN has the advantage you still have access to the columns in table_A)
it is never wise to use $_POST-vars directly in your queries, this is a serious security risk (SQL injection.)

Categories