Make a select query from two table with where clause. - php

I have two variables $code and $name. $code probably have tutor's code or institute's code and$name also probably have tutor's name or institute's name.
This is the way the names come to $code and $name
// Check Tutor or Institute
if ( $tutorCode && $tutorName) {
$code = $tutorCode;
$name = $tutorName;
} elseif ( $instituteCode && $instituteName) {
$code = $instituteCode;
$name = $instituteName;
}
My problem is I need to get email address from contact table according to this $code and $name. Need to check two table tutor and institute which belong to code and name.
tutor and institute table have contact_id and contact table also have contact_id.
tutor table have tutor_code and tutor_name.
institute table have institute_code and institute_name
I tried something like this. but can't check in both tables.
$q = "SELECT email FROM tutor
WHERE tutor_code = $code AND tutor_name = $name"
Hope someone will help me.
Thank you.

you can UNION both tables
SELECT email, code, name
FROM
(
SELECT email, tutor_code as code, tutor_name as Name FROM tutor
UNION ALL
SELECT email, institute_code as code, institute_name as Name FROM institute
) sub
WHERE code = $code AND
name = '$name'
or
SELECT s.*, c.*
FROM
(
SELECT contact_ID,
tutor_code as code,
tutor_name as Name,
'TUTOR' sourceTbl
FROM tutor
WHERE tutor_code = $code AND
tutor_name = '$name'
UNION ALL
SELECT contact_ID,
institute_code as code,
institute_name as Name,
'INSTITUTE' sourceTbl
FROM institute
WHERE institute_code = $code AND
institute_name = '$name'
) s
INNER JOIN contact c
ON s.contact_ID = c.contact_ID
keep it mind that it will return duplicate record if both records exists on both table because of specifying ALL in the UNION. If you want to get only unique records, remove ALL.

You should read up on using joins in mysql.
http://dev.mysql.com/doc/refman/5.0/en/join.html
And for both the institute and tutor part, you could use a UNION or joins.
In your case it would look something like this:
$q = "SELECT c.email
FROM contact c
LEFT JOIN tutor t on t.contact_id = c.contact_id
LEFT JOIN institute i on i.contact_id = c.contact_id
WHERE
(
(t.tutor_code = $code AND t.tutor_name = $name) OR
(i.institute_code = $code AND i.institute_name = $name) OR
)";

to look at your query i am noticing that there is issue for $code and $name values.
you need to add $code and $name inside double quote or single quotes.

Related

Error: Join in MySql, PHP

I have two tables in mysql one is quote and the fields are quote_id, status, created and submit_by. in submit_by field i am saving username of the employee and in employee table the fields are firs_name, last_name, username, password. I want to show in a php table the employee first name instead of username of the employee.
full quote table stucture
full employee table sructure
this is the code i am using but not getting any result
$sql = "SELECT q.quote_id, q.client_name, q.status, e.first_name
FROM `quote` AS q
LEFT JOIN `employee` AS e ON q.submit_by = e.username";
Use this one
$sql = "SELECT * , employee.first_name FROM quote
LEFT JOIN employee ON quote.submit_by = employee.username ORDER BY quote.client_name";
$result = $dbLink->query($sql);
try this:
SELECT quote.quote_id, quote.client_name, quote.status, employee.first_name FROM quote
LEFT JOIN employee ON quote.submit_by = employee.username ORDER BY quote.client_name;
You can use below Query to get the result.
SELECT q.`quote_id`, q.`client_name`, q.`status`, e.`first_name` FROM `quote` q , `employee` e WHERE q.`submit_by` = e.`username`;

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

Get the names of IDs from different table

I have an array with a lot of data from a database. In the array, there are two fields called teameinsid and teamzweiid. The query is a very simple one :
$spiel = mysql_query("select teameinsid, teamzweiid from begegnung", $connection) or die("Keine passende Begegnung");
What I need is to search in the database for the names of these IDs. The names are in a different table.
What I have now is the following:
while($tmp = mysql_fetch_array($spiel)){
$teins = $tmp['teameinsid'];
$tzwei = $tmp['teamzweiid'];
}
So I know the two IDs, but I don't know where to save the names. If I try:
$name = mysql_query("select name from team where teameinsid = $teins", $con)
it gets overwritten every time. How can I manage this?
EDIT:
Database Scheme:
Table Team : id, name
Table Begegnung: id, teameinsid, teamzweiid
I tested this, and it works if your query in $speil is this:
SELECT B.*, T1.name AS teamnameeins, T2.name as teamnamezwei FROM begegnung AS B
JOIN team AS T1 ON T1.id = B.teameinsid
JOIN team AS T2 ON T2.id = B.teamzweiid
http://dev.mysql.com/doc/refman/5.0/en/join.html
You should use your code now like this:
while($tmp = mysql_fetch_array($spiel)){
$teins = $tmp['teamnameeins'];
$tzwei = $tmp['teamnamezwei'];
}
change your code like this
while($tmp = mysql_fetch_array($spiel)){
$teins[] = $tmp['teameinsid'];
$tzwei[] = $tmp['teamzweiid'];
}
now
$ids=implode ( ',' , $teins);
$name = mysql_query("select name from team where teameinsid in($ids)", $con)

Help construct a simple query Using 3 tables

Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1

PHP And MYSQ help

ok here is my php and mysql code:
where it is bold i wanted to the the uid from the online table and if it in there
where online.uid = '' i needed so it put the uid in there.
$sql = ("select accounts.id,
accounts.tgid,
accounts.lastactivity,
cometchat_status.message,
cometchat_status.status,
**online.uid**
from friends_list join accounts
on friends_list.fid = accounts.id
left join cometchat_status
on accounts.id = cometchat_status.userid
where friends_list.status = '1'
and **online.uid = ''**
and friends_list.uid = '".mysql_real_escape_string($userid)."'
order by tgid asc");
#sledge identifies the problem in his comment above (I'm not sure why he didn't post an answer).
You are selecting a column from the online table, but you don't include it in your FROM clause. You have to query from a table in order to reference its columns in other parts of the query. For example:
$sql = ("select accounts.id,
accounts.tgid,
accounts.lastactivity,
cometchat_status.message,
cometchat_status.status,
online.uid
from friends_list
join accounts on friends_list.fid = accounts.id
join online on ( ??? )
left join cometchat_status
on accounts.id = cometchat_status.userid
where friends_list.status = '1'
and online.uid = ''
and friends_list.uid = '".mysql_real_escape_string($userid)."'
order by tgid asc");
You need to fill in the join condition, because there's not enough information in your original post to infer how the online table is related to other tables.
PS: Kudos for using mysql_real_escape_string().

Categories