MySQL join and associative array? - php

I am trying to do a MySQL join like so,
$q = $dbc -> prepare("SELECT m.* a.username FROM mailbox m JOIN accounts a (m.msgFrom = a.id) WHERE msgTo = ? AND sent = '0'");
$q -> execute(array($user['id']));
while ($msg = $q -> fetch(PDO::FETCH_ASSOC)) {
echo $msg['username'];
}
I would like to pull the users' username from the table accounts rather than just display the id from the table mailbox, I get the array performing a while loop on the query,
This doesn't seem to work though, any ideas?

You forgot the on in the join condition try this:
SELECT m.*, a.username
FROM mailbox m JOIN accounts a on (m.msgFrom = a.id)
WHERE msgTo = ? AND sent = '0'

Related

Get userID from database

I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author).
I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post.
I was thinking to do a join or something but I can't figure this out.
Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Try something like this, usng INNER JOIN :
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !

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

combining two mysql queries in php

I am creating a dashboard to keep me updated on call agent status.an agent will have multiple records in the log. I need to pull the most recent status from the agent log. The only way I have found is to query the agent table to pull the agents with status changes made today and then query the agent log table to pull the most recent status.
is there a way to combine the two queries.? Here are my queries
$sql_get_agents = "SELECT id FROM agent WHERE lastchange LIKE '{$today}%'";
if($dta = mysql_query($sql_get_agents)){
while($agent = mysql_fetch_assoc($dta)){
$curr_agent[] = $agent;
}
foreach($curr_agent as $agents_online){
$get_status_sql = "SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid = '{$agents_online['id']}'";
if($dta2 = mysql_query($get_status_sql)){
while($agent_status = mysql_fetch_assoc($dta2)){
$curr_status[] = $agent_status;
}
}
}//end for each
return $curr_status;
}//end if
Why don't you join the 2 queries into one adding the WHERE lastchange LIKE '{$today}%' condition in the second query?
Using the IN clause should work :
"SELECT a.firstname,a.lastname,al.agentid,al.agent_statusid,s.id as statusid,s.status,MAX(al.datetime) as datetime FROM agent_log al
INNER JOIN agent a ON al.agentid = a.id
INNER JOIN agent_status s ON a.agent_statusid = s.id
WHERE al.agentid IN (SELECT id FROM agent WHERE lastchange LIKE '{$today}%');
You were close with what you have. This will get rid of the need to do both queries, or query in a loop.
edit: adding example code to loop over the results as well.
edit2: changed query.
$query = "SELECT
a.firstname,
a.lastname,
al.agentid,
al.agent_statusid,
s.id as statusid,
s.status,
MAX(al.datetime) as datetime
FROM agent a
LEFT JOIN agent_log al ON al.agentid = a.id
LEFT JOIN agent_status s ON a.agent_statusid = s.id
WHERE a.lastchange LIKE '{$today}%'";
$status = array();
$results = mysql_query( $query );
while( $agent = mysql_fetch_assoc( $results ) )
$status[] = $agent;
print_r( $status );

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']

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