I am programming a chat room on my site but I am really new to php. I want users to be able to chat with the users that played in the same teams of a game (knowing that users can have participated together to differents team) and who work in the same area.
Assume there are three tables : the account user's table, the area's t able, games'table
I have a function that returns my query that looks like
function myfunction($userid){
$games_user=mysql_query('select theme from games where games.userid="'.$userid.'"');
$games_theme = mysql_fetch_array($games_user);
$sql = ("select userid, username, area.userid
from account
left join area
on account.userid = area.userid
left join games
on account.userid = games.userid
where account.userid <> '".mysql_real_escape_string($userid)."' and '".(in_array(games.theme,$games_theme))."' and area.userid=1
);
return $sql;
}
Reformatted:
$sql = "
SELECT userid, username, area.userid
FROM account
LEFT JOIN area ON account.userid = area.userid
LEFT JOIN games ON account.userid = games.userid
WHERE account.userid <> '".mysql_real_escape_string($userid)."'
AND '".(in_array(games.theme,$games_theme))."'
AND area.userid = 1
";
But it really doesn't work, I think I have syntax problems.
I don't really understand how in_array is indexed, and I don't know how to do in a simpler way that query
Can anybody help ?
I'm still not entirely sure what you are doing, but I think this is what you want; you can do this in a single query:
<?php
function myfunction($userid){
$id = mysql_real_escape_string($userid);
$sql = "SELECT userid, username, area.userid
FROM account
LEFT JOIN area
ON account.userid = area.userid
LEFT JOIN games
ON account.userid = games.userid
WHERE account.userid<>'$id' AND area.userid=1
AND games.theme IN (SELECT theme FROM games WHERE games.userid='$id')
";
return $sql;
}
?>
Related
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']
i have this piece of code that selects all users from the table and another sql statement that counts the number of records for every user. the problem I'm facing is that i have a sql in a foreach loop which is not good for performance but i wasn't able to combine both of them in one statement. any advise?
$query = $db->getAll("SELECT * FROM users");
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$query2 = $db->numRows("SELECT * FROM signups AS s INNER JOIN users AS u ON s.userid=u.id WHERE u.id={$v['id']}");
$tpl->setVariable('total',$query2);
$tpl->setVariable($v);
$tpl->parseCurrentBlock();
}
Try this query against your DB:
SELECT u.id, COUNT(s.*)
FROM users u
LEFT JOIN signups s ON s.userid = u.id
GROUP BY u.id
I hope I got it right. I have no SQL DB to test it right here. Important: You have to group by each field you select that is no aggregate.
Edit:
If it is not fast enough yet, an index on signups.userid may help. This is hypothetic, however, so you should check the Execution Plan your query engine generates.
$query = $db->getAll("
SELECT u.id, u.name, COUNT(*) total
FROM signups AS s RIGHT JOIN users AS u ON s.userid=u.id
GROUP BY u.id, u.name
ORDER BY u.name
");
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$tpl->setVariable('total', $query['total']);
// ...
$tpl->parseCurrentBlock();
}
If I understand good your problem, initialize variable and in loop increase it.
int i;
foreach($query as $v){
$tpl->setCurrentBlock('useri');
$query2 = $db->numRows("SELECT * FROM signups AS s INNER JOIN users AS u ON s.userid=u.id WHERE u.id={$v['id']}");
$tpl->setVariable('total',$query2);
$tpl->setVariable($v);
$tpl->parseCurrentBlock();
i++;
}
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
I have a query that retrieves the name of each friend a user has by joining that of friends and users tables. I have another table that stores active users. I need to retrieve friends that are active and not active but for some reason I am drawing a blank. If I have a list of all friends and a list of active friends, can I subtract active from all to be left with offline? All I Want to do basically is have two tabs. Under one will be offline friends. Under the other will be online friends. If anyone has any useful suggestions, I would appreciate it.
$sql = 'SELECT * FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
WHERE friendships.user_id = ?';
$stmt5 = $conn->prepare($sql);
$result=$stmt5->execute(array($userid));
$count=$stmt5->rowCount();
//user has more than 0 friends
if ($count>0){
while ($row = $stmt5->fetch(PDO::FETCH_ASSOC)) {
$online=htmlspecialchars( $row['username'], ENT_NOQUOTES, 'UTF-8' );
//check whos online
$sql = 'SELECT * FROM active_users
WHERE username=?';
$stmt7 = $conn->prepare($sql);
$result=$stmt7->execute(array($online));
$count=$stmt7->rowCount();
while ($row = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$activeuser=$row['username'];
}
}
This code just retrieves active users but hopefully gives an idea of structure.
Could you do a "not in" clause? Without knowing the layout of your database, I'm thinking something like this:
SELECT * FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
WHERE friendships.user_id = ?
AND users.id NOT IN (
SELECT user_id FROM active_users
)
Using SQL to do this 'not in' is probably the best solution.
You could also do this in code if you really want to if the results are ordered. Just loop through the all users list, grab the first result from the active users list, and whenever there's a match, put that on the active users list and grab the next active user. Put every non-match into the inactive users list and only fetch from the all users list.
Something like this might tell you both lists in one shot:
SELECT users.username, active_users.username AS active FROM users
LEFT JOIN friendships
ON friendships.friend_id = users.id
LEFT JOIN active_users ON users.username = active_users.username
WHERE friendships.user_id = ?
Inactive users would return NULL in the active columns, where active would not.
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().