subjects.id is overriding users.id in the JSON response whenever i add subjects.idto the select in the query.
How can i show my both users.id and subject.id in the response
$sql = "SELECT users.id,users.name,users.date,subjects.id FROM tb_user AS users INNER JOIN
tb_subjects AS subjects ON users.id = subjects.userid WHERE users.id = '$userid'";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
if(empty($user)) {
$response->getBody()->write
('
{
"error":
{
"message":"Invalid"
}
}');
} else {
$response->getBody()->write(json_encode($user));
}
} catch(PDOException $e) {}
current output
{
"id": "1",
"name": "joe",
"date": "2017-07-22 18:37:37"
}
expected output
{
"id": "1",
"name": "joe",
"subjectid": "4",
"date": "2017-07-22 18:37:37"
}
To get around the problem of a result set with two id columns, give the subject id column an alias of subjectid:
SELECT
users.id,
users.name,
users.date,
subjects.id AS subjectid
FROM tb_user AS users
INNER JOIN tb_subjects AS subjects
ON users.id = subjects.userid
WHERE users.id = '$userid'
Most databases seem to tolerate a result set which has two columns by the same name. But this would fail if it were to happen in a subquery in which you tried to also select that duplicate column. It looks like PHP is just deciding to choose one of the id columns though the best thing to do here is to fix the duplicate name problem in the query.
Edit:
If you wanted to get the latest subject, as indicated by its time column, you could slightly modify your query to use another join:
SELECT
users.id,
users.name,
users.date,
s1.id AS subjectid
FROM tb_user AS users
INNER JOIN tb_subjects s1
ON users.id = s1.userid
INNER JOIN
(
SELECT userid, MAX(time) AS max_time
FROM tb_subjects
GROUP BY userid
) s2
ON s1.userid = s2.userid AND
s1.time = s2.max_time
WHERE users.id = '$userid'
The subquery in the new join finds the latest time for each user. But this still does not give us the subject id which we actually want. To get this, we can access the first tb_subjects table, which however has been reduced after this new join to only records having the most recent message time. One caveat here: if you had a tie for most recent message my query would return all such ties. We could workaround this, but it would be more work.
Related
I develop a chat system where students and staff can exchange different messages. I have developed a database where we have five tables: the staff table, the student, the message and two mapping tables the staff_message and stu_message. These tables contain only the student/staff id and the message id.
My problem is that I cannot order the messages. I mean that I cannot figure out how can I make one SQL statement that will return all messages and be ordered by for example the ID. The code that I have made is this:
$qu = mysqli_query($con,"SELECT * FROM stu_message");
while($row7 = mysqli_fetch_assoc($qu)){
$que = mysqli_query($con, "SELECT * FROM student WHERE studentid =".$row7['stu_id']);
while($row8 = mysqli_fetch_assoc($que)) {
$username = $row8['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row7['mid']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
$query2 = mysqli_query($con, "SELECT * FROM staff_message");
while($row3 = mysqli_fetch_assoc($query2)){
$query = mysqli_query($con, "SELECT * FROM staff WHERE id =".$row3['staff_id']);
while($row5 = mysqli_fetch_assoc($query)) {
$username = $row5['username'];
}
$query3 = mysqli_query($con, "SELECT * FROM message WHERE id=".$row3['m_id']);
while($row6 = mysqli_fetch_assoc($query3)) {
echo $row6['date']."<strong> ".$username."</strong> ".$row6['text']."<br>";
}
}
?>
The result is different from that I want. To be more specific first are shown the messages from the students and then from the staff. My question is, is there any query that it can combine basically all these four tables in one and all messages will be shown in correct order? for example by the id?
Thank you in advance!
First, use JOIN to get the username corresponding to the stu_id or staff_id, and the text of the message, rather than separate queries.
Then use UNION to combine both queries into a single query, which you can then order with ORDER BY.
SELECT u.id, u.text, u.username
FROM (
SELECT s.username, m.text, m.id
FROM message AS m
JOIN stu_message AS sm ON m.id = sm.mid
JOIN student AS s ON s.id = sm.stu_id
UNION ALL
SELECT s.username, m.text, m.id
FROM message AS m
JOIN staff_message AS sm ON m.id = sm.m_id
JOIN staff AS s ON s.id = sm.staff_id
) AS u
ORDER BY u.id
So I have two tables, one storing the username and the other with their personal info. What I'm trying to get is a result where, I want to take the current active username and join it with the personal info table to get the ID, Username + their basic info to appear in a table. I came up with the query after googling, but it seems that I did something wrong. Can someone tell me what I did wrong?
users = the table that contain username
userinfo table with their basic info
$username is basically a variable that was stored in the $SESSION
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName,
FROM users
WHERE users.Username = $username
INNER JOIN userinfo
ON users.UserID=userinfo.UserID");
?>
Assuming I have the parse data to table coding right below that specific code, what is wrong with the query?
Basically the error I keep getting is error #1064 at line #2 (when I run the query without the php code). Thanks in advance!
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username
");
?>
Try this
<?php
$query = mysql_query("
SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName,
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username");
?>
The syntax is -
SELECT col, ...
FROM <tbl_name> AS t1
INNER JOIN <join_tbl_name> AS t2
ON t1.col = t2.col
WHERE <cond>
See the below code. If you print it, you will find where error occurs.
echo $query = mysql_query("SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName FROM users WHERE users.Username = '$username' INNER JOIN userinfo ON users.UserID=userinfo.UserID");
or use
$sql="SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName FROM users WHERE users.Username = '$username' INNER JOIN userinfo ON users.UserID=userinfo.UserID";
if(!mysql_query($sql,$con))
{
echo "Unexpected Error <br/>";;
die (mysql_error());
}
where $con is mysql connection statement.
You have an extra comma at the end of field select. Try removing that part:
$query = "SELECT users.UserID, users.Username, userinfo.FirstName, userinfo.LastName
FROM users
INNER JOIN userinfo
ON users.UserID=userinfo.UserID
WHERE users.Username = $username";
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 );
I have coded up an example of exactly what the MySQL query needs to do, I had tried to combine the two queries but I didn't have any success with doing so. Basically, what this does is selects all users that $session is not friends with already.
I don't know how much I need to explain as far as my table structure goes, as you can see what I need to do using my query below, but basically my friends table only has one row for each friendship. (a friendship is only valid if the state is 1 and the CASE statement is necessary to get the friends ID from the friendship, since my table does only have one row for a friendship.
$getUsers = mysql_query("SELECT id FROM users WHERE id!=$session");
$getFriends = mysql_query("SELECT CASE WHEN userID=$session THEN userID2 ELSE userID END AS friendID
FROM friends
WHERE (userID=$session OR userID2=$session)
AND state='1'");
$usersArray = array();
$friendsArray = array();
while($usersC = mysql_fetch_array($getUsers))
{
$usersID = $usersC['id'];
array_push($usersArray, $usersID);
}
while($usersF = mysql_fetch_array($getFriends))
{
$friendID = $usersF['friendID'];
array_push($friendsArray, $friendID);
}
print_r(array_merge(array_diff($usersArray, $friendsArray), array_diff($friendsArray, $usersArray)));
You want an anti-join, which you can effect through an outer join and a filter for records where the joined table is NULL:
SELECT users.id
FROM users LEFT JOIN friends f
ON (f.userID = $session AND f.userID2 = users.id AND f.state='1')
OR (f.userID = users.id AND f.userID2 = $session AND f.state='1')
WHERE f.userID IS NULL AND f.userID2 IS NULL
AND users.id <> $session
See it on sqlfiddle.
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']