Help construct a simple query Using 3 tables - php

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

Related

select from two mysql tables where column value is similar and id is retrieved from previous page

i have a question. my english isn't well. so i hope i explain well...
i have two tables, tbl_home and tbl_office, the question is
how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..
$a=$_POST['home_id']
the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form
<?php
$sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);
while($row = $result2->fetch_assoc()){
$a=$row['case_no'];
$bc=$row['colour'];
echo " $a <br/> ";
echo " $bc2 <br/>";
?>
is the select statement above correct??
soo, i just want anybody to take a look a this specific statement and how to make it right
$sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";
You need inner join to use:
" SELECT t_office.home_id,t_office.case_no,t_office.name FROM tbl_office
t_office INNER JOIN tbl_home t_home ON t_office.case_no = t_home.case_no;
where t_office.case_no ='$a'";
u can use "inner join" for example:
"SELECT t.home_id,t.case_no,t.name FROM tbl_office
t INNER JOIN tbl_home h ON h.case_no = h.case_no"
**select tbl_home.name,tbl_office.case_no,tbl_office.color from tbl_office
INNER JOIN tbl_home on tbl_office.case_no = tbl_home.case_no
where tbl_office.case_no ='$a';**
I hope this will be working fine until $a(case_no) value is existed in tbl_home or else it doesn't give any rows

Make multiple queries in codeigniter and the results based in the first one

I want to display all rows of table article, and for each of article row i want get the SUM of votes from another table (likes), and this with one query.
Here what i have:
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,SUM(likes.votes) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
But my problem with this query, i get only one row ! because in table likes there only one row ...
I want to display results based on article table (i have about 50 rows in it)... and if there nothing related to votes for a specific article, we show (0 votes).
Thank you.
Add group by to the code :
$query = "SELECT article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date, SUM(likes.votes) as upvotes FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";
$query .= " GROUP BY article.id";
Or use codeigniter method:
$this->db->select("article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date");
$this->db->select("SUM(likes.votes) as upvotes", false);
$this->db->from("article");
$this->db->join("users","article.user_id = users.user_id");
$this->db->join("likes","likes.article_id = article.id");
$this->db->group_by("article.id");
$query = $this->db->get();
return $query->result_array();
A stored function is a special kind stored program that returns a single value. You use stored functions to encapsulate common formulas or business rules that are reusable among SQL statements or stored programs.
Here you query should
$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,custom_SUM(article.id) as upvotes
FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
and custom mysql function
DELIMITER $$
CREATE FUNCTION custom_SUM(p_article_id int(11)) RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE likes varchar(10);
SET likes =(select sum(likes.votes) from likes where likes.article_id=p_article_id);
RETURN (likes);
END
refer link here http://www.mysqltutorial.org/mysql-stored-function/

How can I convert these two queries in a loop into a single JOINed query?

I am currently trying to get data from my table (mostKills by Weapon in a table with over 300 kills). Initially I did a normal query
$q = $mysql->query("SELECT * FROM `kills`") or die($mysql->error);
but when I tried to
$query2 = $mysql->query("SELECT `killerID`, COUNT(`killerID`) AS tot_kills FROM `kills` WHERE `killText` LIKE '%$gun%' GROUP BY `killerID` ORDER BY `tot_kills` DESC;") or die($mysql->error);
$kData = $query2->fetch_assoc();
$query3 = $mysql->query("SELECT `Username` FROM `players` WHERE `ID` = '" . $kData['killerID'] . "'") or die($mysql->error);
$uData = $query3->fetch_assoc();
$array[$gun]['Kills']++;
$array[$gun]['Gun'] = $gun;
$array[$gun]['BestKiller'] = $uData['Username'];
$array[$gun]['killAmount'] = $kData['tot_kills'];
function sortByKills($a, $b) {
return $b['Kills'] - $a['Kills'];
}
usort($array, 'sortByKills');
foreach($array as $i => $value)
{
// table here
}
I had to do it in a while loop, which caused there to be around 600 queries, and that is obviously not acceptable. Do you have any tips on how I can optimize this, or even turn this into a single query?
I heared JOIN is good for this, but I don't know much about it, and was wondering if you guys could help me
Try this...
I added a inner join and added a username to your select clause. The MIN() is just a way to include the username column in the select and will not have an impact on you result as long as you have just 1 username for every Killerid
SELECT `killerID`
, COUNT(`killerID`) AS tot_kills
, MIN(`Username`) AS username
FROM `kills`
INNER JOIN `players`
ON `players`.`id` = `kills`.`killerid`
WHERE `killText` LIKE '%$gun%'
GROUP BY `killerID`
ORDER BY `tot_kills` DESC
SELECT kills.killerID, count(kills.killerID) as killTotal, players.Username
FROM kills, players
WHERE kills.killText
LIKE '%$gun%'
AND players.ID` = kills.killerID
GROUP BY kills.killerID
ORDER BY kills.tot_kills DESC
Here is a good place to learn some more about joins.
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
The best way is to have your own knowledge so you can be able to tune up your select queries.
Also put more indexes to your DB, and try to search and join by index.

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

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