Inner/Left join with two different where clauses - php

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 = ?"

Related

Using form to show all records where certain value is greater than X

For this problem I need to make a PHP page where the user can search an invoice table by inputting a "quantity" value. The form then takes that quantity and spits out a table with the name, invoice number, quantity, and item description for all invoices where the quantity exceeds the quantity the user submitted.
For the most part I have my page set up and working fine. Where I'm getting stuck is on the query side -- specifically, the code below is providing me a list of invoices where the quantity is identical to the input quantity.
I've tried changing "WHERE ii.quantity LIKE ?" to "WHERE ii.quantity > ?" but all that does is provide me a list of all invoices without filtering by the user submitted quantity.
$query =
"SELECT c.first_name, c.last_name, ii.invoice_id, ii.quantity, it.description
FROM `c2092`.`customer` c
JOIN `c2092`.`invoice` i ON c.customer_id = i.customer_id
JOIN `c2092`.`invoice_item` ii ON ii.invoice_id = i.invoice_id
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity LIKE ?
ORDER BY ii.invoice_id";
This is too complex query. Try to make explain on it. I am sure it will use filesort, and even temp table.
The better approach is to make several queries:
$invoiceItems = $db->query(
"SELECT ii.invoice_id, ii.id, ii.quantity, it.description
FROM `c2092`.`invoice_item` ii
JOIN `c2092`.`item` it ON it.item_id = ii.item_id
WHERE ii.quantity > ?
ORDER BY ii.invoice_id");
$invoiceItemMap = [];
$invoiceIds = [];
foreach ($invoiceItems as $invoiceItem) {
$invoiceItemMap[$invoiceItem['invoice_id']][] = $invoiceItem;
$invoiceIds[$invoiceItem['invoice_id']] = $invoiceItem['invoice_id'];
}
$invoiceIds = array_values($invoiceIds);
$userInvoices = $db->query(
"SELECT c.first_name, c.last_name, i.invoice_id
FROM `c2092`.`invoice` i
JOIN `c2092`.`customer` c ON c.customer_id = i.customer_id
WHERE i.id IN (".implode(',', $invoiceIds).")");
$result = [];
foreach ($userInvoices as $row) {
$result[] = array_merge($row, $invoiceIds[$row['invoice_id']]);
}
Hello,
What is the value of your variable?
Prefer the use of named parameter instead of ? syntax.

Use INNER JOIN / JOIN for multiple query

What I have at the moment is to match the case from law_case, as in the database scheme below.
My code:
$query1 = "SELECT * FROM law_case WHERE id =?";
$query1vals = array($_GET['id']);
$ids = $adb->selectRecords($query1, $query1vals, false);
$a = $ids['case_type_id'];
$b = $ids['funding_pref'];
#
$query2 = "SELECT type_name FROM case_type WHERE id =?";
$query2vals = array($a);
$ids1 = $adb->selectRecords($query2, $query2vals, false);
$d = $ids1['type_name'];
#
$query3 = "SELECT * FROM expertise WHERE expertise_desc =?";
$query3vals = array($d);
$ids2 = $adb->selectRecords($query3, $query3vals, false);
$c = $ids2['id'];
#
$query4 = "SELECT * FROM individual_expertise WHERE expertise_id =?";
$query4vals = array($c);
$ids3 = $adb->selectRecords($query4, $query4vals, false);
$e = $ids3['individual_id'];
#
$query5 = "SELECT * FROM individual WHERE id =?";
$query5vals = array($e);
$ids4 = $adb->selectRecords($query5, $query5vals, false);
$f = $ids4['network_member_id'];
#
$query6 = "SELECT * FROM network_member WHERE id =?";
$query6vals = array($f);
$ids5 = $adb->selectRecords($query6, $query6vals, false);
And what it does is it only gets one network_member.
I want to use INNER JOIN, JOIN or LEFT JOIN and use a while looking to get the different member_name and the URL for each network_member or who's individual has the same expertise_id from the individual_expertise table.
I'm new to JOIN and tried this code but it doesn't work:
$sql = "SELECT member_name, url
FROM individual_expertise
LEFT JOIN individual
USING (individual_id)
LEFT JOIN network_member
USING (network_member_id)
WHERE expertise_id = ?";
$ids3 = $adb->selectRecords($sql, $query4vals, false);
echo $ids3['member_name'];
You need to get an overview of JOIN types. You have to build a query using INNER, LEFT, RIGHT, FULL joins depending on your logical requirements. You can assume that INNER join is equal to && or AND operators in conditional statements, I mean records must match in both tables.
While, LEFT join will return all rows from left table of join and matched rows from right table of join. And RIGHT is inverse of LEFT.
And FULL join is an example of || or OR in operators in conditional statements. I mean either a match in both tables.
So you have to join depending on logic you require.
See here
Do you know the difference between INNER JOIN and LEFT JOIN? I think you don't. You need an INNER JOIN here.
I think this is the right solution for your question:
SELECT
network_member.member_name,
network_member.url
FROM
network_member
INNER JOIN
individual ON individual.network_member_id = network_member.id
INNER JOIN
individual_expertise ON individual_expertise.individual_id = individual.id
WHERE
individual_expertise.expertise_id = ?

Mysql Join two Id's to get there Usernames

Im trying to get in Array that contains the results from a MYSQL query.
I have 2 ids stored in the table hitlist user_id and mark_id
they need to join in the table users to retrieve there usernames that match there id's and in the future other variables.
i have this working in a weird way and was hopeing to get this working in a more efficent simple way similar to this
$Hitlists = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id AND hitlist.mark_id = users.id")->fetchAll();
This is the code i have that is working...for now it looks like it might give me problems later on.
<?php
$index = 0;
$Hitlists = array();
$st = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.user_id = users.id")->fetchAll();
$sth = $db->query("SELECT * FROM hitlist JOIN users ON hitlist.mark_id = users.id")->fetchAll();
foreach($st as $id)
{
$Hitlists[] = $id;
}
foreach($sth as $id)
{
$Hitlists[$index]['markedby'] = $id['username'];
$Hitlists[$index]['mark_id'] = $id['mark_id'];
$index++;
}
The way you are joining the table is wrong. You can get the exact records you want, you need to join users table twice to get the username of each ID
SELECT a.*,
b.username User_name,
c.username mark_name
FROM hitlist a
INNER JOIN users b
ON a.user_id = b.id
INNER JOIN users c
ON a.mark_id = c.id
and you can access
$result['User_name']
$result['mark_name']

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