This one's probably easy:
I have two variables:
$sender_id
$receiver_id
Those ID's are stored and assigned to a user in tblusers. I have no problem selecting one-at-a-time:
$data = mysql_query("SELECT * FROM tblusers WHERE usrID='$receiverID'") or die(mysql_error());
while($row = mysql_fetch_array( $data ))
{
echo $row['usrFirstName'];
echo $row['usrLastName'];
}
However, how would I select both rows (one for senderID and receiverID) so that I can gain access to further information on both those users. Sort of like a "SELECT within a SELECT".
Thanks!
SELECT * FROM tblusers WHERE usrID='$receiverID' or usrID='$sender_id'
EDIT: clarification
while($row = mysql_fetch_array( $data ))
{
if($row['usrID'] == $receiverID) {
echo "Receiver: " . $row['usrFirstName'] . " " . $row['usrLastName'];
} else {
echo "Sender: " . $row['usrFirstName'] . " " . $row['usrLastName'];
}
}
If you need to differentiate which is the receiver and which is the sender:
select
'Receiver' as UserType,
*
from
users
where
usrid = $receiver_id
union all
select
'Sender' as UserType,
*
from
users
where
usrid = $sender_id
This will return:
UserType | UsrID | Name
Receiver | 23 | John Smith
Sender | 42 | Adam Douglas
Of course, with two rows, you can always just compare the ID's to figure that out, too. This is mainly to make scaling easier if you have a larger result set than just two rows.
SELECT * FROM tblusers WHERE usrID IN ($receiverID, sender_id)
Related
I have a database (GAMES) with userid, name, sports and points.
user1, football, 10 points -
user1, Basketball, 5 points
user2, footbal, 8 points -
user2, Baketball, 3 points
To get the rank of each user by each sports, I am using the following code which is working perfect:
$sql = "SELECT
sports,
FIND_IN_SET(footbal, (
SELECT GROUP_CONCAT(sports
ORDER BY points DESC)
FROM ".GAMES."
)
) AS rank
FROM ".GAMES."
WHERE userid = 1
";
Results:
user1 (1) (1 is the rank)
When I use user2 in WHERE I get: user2 (2)
Now I want a list like this (For more than 1000 users):
1- User1 (1)
2- User2 (2)
3- User15 (44)
3- ....
Any help will be appreciated. I you need more explanation, just ask.
I would do something like this:
$sqls = array();
foreach ($sports as $sport) {
$sqls[] = "SELECT name FROM ".GAME." WHERE sports='".$sport."' ORDER BY points ASC"
}
Then loop through slqs variable to get all the lists.
And finally, to get the parenthesis part, I would do when I will print the list.
You could have 1 select like this:
$sql = 'SELECT * from table_GAMES WHERE points >= 1000 ORDER BY name'
The result would have all users with more than or equal to 1000 sorted alphabetically. You can then display it like this:
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name'];
echo ' (' . $row['points'] . ')';
}
MySQL does not really implement ranking in a convenient way. This is discussed, for example, here: ROW_NUMBER() in MySQL
In that thread linked above you can see some solutions you could try, or alternatively you could use some simpler SQL to get an ordered list and use PHP to calculate/count the ranks:
// ...
$sql = 'SELECT userid, sports, SUM(points) AS total_points FROM games GROUP BY userid, sports ORDER BY sports, SUM(points) DESC';
$result = $mysqli->query($sql);
$rank = null;
$last_sport = null;
$sports_ranking = array();
while($row = $result->fetch_object()) {
if($row->sports == $last_sport) {
$rank++;
} else {
$rank = 1;
}
$sports_ranking[$row->sports][] = array(
'userid' => $row->userid,
'rank' => $rank,
'total_points' => $row->total_points
);
}
echo('<pre>'); print_r($sports_ranking); echo('</pre>');
// ...
Wouldn't this work?
"SELECT * FROM GAMES WHERE userid = ".$userid." ORDER BY points DESC"
I don't see why you would need to use anything else, as you are just ordering by their points.
or if you also want to specify a sport,
"SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC"
You would need to use an array to loop through each sport then just use the above query again.
e.g.
$ranks = mysql_query("SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC", $database);
$count = 1;
while(list($userid, $name, $sport, $points) = mysql_fetch_row($ranks)) {
//formatting here. table row, paragraph etc or:
echo "$count - $name ($userid)";
$count++;
}
I have a table of which I must select information using a MySQLi Query and push it to the end of a PHP array.
The table is in this format:
table = friends
id user1 user1_id user2 user2_id datemade accepted
1 name1 1 name2 2 2015-05-27 03:24:32 1
2 name3 3 name2 2 2015-05-27 03:24:32 1
3 name3 3 name1 1 2015-05-27 03:24:32 1
4 name4 4 name2 2 2015-05-27 03:24:32 1
id = an auto_incrementing number to keep track of everything
user1 = the person's name that asks for friendship
user1_id = that person's special unique id
user2 = name of the person that accepts/decline's friendship
user2_id = that person's special unique id
datemade = the date it was made :P
accepted = did he accept? (don't worry about this)
I want to select all users that are friends with $u.
In this example, $u's id is 1 (name is name1).
After running the query it would push it to the end of friend_array.
So if I printed this array the output would be:
2, 3
Since, id=1 is friends with id=2 and id=3
What query should I do and how would I push that to an array (I know about about array_push but I do not know how to implement it)?
Please try this code. It will return the array for all user's friends.
$sql = "SELECT user1 AS user FROM friends UNION SELECT user2 AS user FROM friends";
$data = mysqli_query($sql);
while ($v = mysqli_fetch_assoc($data)) {
$sql = mysqli_query("SELECT * FROM `friends` where (user1 = '" . $v['user'] . "' or user2 = '" . $v['user'] . "')");
$arr = array();
while ($array = mysqli_fetch_assoc($sql)) {
if ($array['user1'] == $v['user']) {
$arr[$v['user']][] = $array['user2_id'];
} else {
$arr[$v['user']][] = $array['user1_id'];
}
}
}
I finally figured it out!
$sql = "SELECT COUNT(id) FROM friends WHERE user1_id='$log_id' AND accepted='1' OR user2_id='$log_id' AND accepted='1'";
$query = mysqli_query($db_conx, $sql);
$query_count = mysqli_fetch_row($query);
$friend_count = $query_count[0];
//echo($friend_count); //how many friends
if($friend_count < 1){
echo($u." has no friends yet");
} else {
$all_friends = array();
$sql = "SELECT user1_id FROM friends WHERE user2_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user1_id"]);
}
$sql = "SELECT user2_id FROM friends WHERE user1_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user2_id"]);
}
$friendArrayCount = count($all_friends);
}
So it first counts how many friends you have to check if you have any, if you do not a, temp. message appearing saying no friends. If you have some friends it will run a query to check what friends you have is both columns - user1_id and user2_id. It will then finally add everything to the $all_friends array and it then counts how many friends you have.
Thank you to everyone that helped!
i have the following code.
i already try'd some sulotions from the search option, but nothing helped.
all tables have a row called: user_id with data in it, but still the query gives false
The $user variable has the value 29 and in my tables look like this:
+---------+---------+-------+-----------+
+ id | user_id | jaar + kenmerk |
+---------+---------+-------+-----------+
+ 1 | 29 | 2015 + standaard |
+---------+---------+-------+-----------+
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id, watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat, watermangement, energie WHERE user_id = ".$user." AND kenmerk = 'standaard' AND jaar = ".date("Y")."";
$result = mysqli_query($conn, $query);
if($result === false) {
echo 'Query failed';
die();
}
else {
// do something
}
If the field user_id exists in more than one table, you need to prefix the field with the table name in your where clause, too. Otherwise your database will not know in which table it should look for the user_id field. But even after you fixed this error the query will probably not return what you want it to. Have a look at some SQL tutorials that cover the join syntax.
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id, watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat, watermangement, energie WHERE <TABLENAME MISSING>.user_id = ".$user." AND kenmerk = 'standaard' AND jaar = ".date("Y")."";
You may need to join all those tables together to get the user_id condition to work properly:
$query = "SELECT buitenklimaat.user_id, kasklimaat.user_id,
watermangement.user_id, energie.user_id FROM buitenklimaat, kasklimaat,
watermangement, energie
WHERE buitenklimaat.user_id = kasklimaat.user_id
AND buitenklimaat.user_id = watermangement.user_id
AND buitenklimaat.user_id = energie .user_id
AND buitenklimaat.user_id = ".$user." AND kenmerk = 'standaard'
AND jaar = ".date("Y")."";
I have a MySQL query where I am trying to search 2 tables simultaneously. This is for an autocomplete search box that searches for regular clients and business clients. Here is the code:
$query = mysql_query("SELECT * FROM clients WHERE lastname LIKE '$q%' AND agentid = '$agentid'
UNION
SELECT * FROM busclients WHERE busname LIKE '$q%' AND agentid = '$agentid'")or die(mysql_error());
if($query) {
while ($result = mysql_fetch_array($query)) {
$busname = $result['busname'];
print_r($result);
if(isset($busname)){
$description['id'] = 'viewbusiness.php?id=' . $result['ID'];
$description['value'] = $busname ;
array_push($return_arr,$description);
}
else
{
$description['id'] = 'viewclient.php?id=' .$result['ID'];
$description['value'] = $result['lastname'] . ", " . $result['firstname'] ;
array_push($return_arr,$description);
}
}
}
The problem is that the business clients get assigned the table names from the regular clients, so the code never uses the if(isset($busname)) because busname becomes lastname instead, and directs you to the veiwclient page.
SELECT
a.lastname ,
b.busname
FROM clients as a
INNER JOIN
busclients as b
on b.agent_id = a.agent_id
WHERE a.agent_id = $agent_id
AND (a.lastname LIKE '$q%' OR b.busname LIKE '$q%')
By specifically selecting the column names you want from that table, and selecting a blank string for the others, I believe you can get the results you're looking for using something like this:
SELECT firstname, lastname, '' AS busname FROM clients WHERE ... UNION SELECT '' AS firstname, '' AS lastname, busname FROM busclients WHERE ...
I have 2 tables that have been joined using the ID that correlates the data on both tables.
I output the information perfectly.
I output ID and it returns that of the ID column in table_1 - PERFECT.
But now I want to output the ID column in table_2 within the same statement.
How do I now say ID from table_2, not table_1?
Here's some code...
$who = $_SESSION['who'];
$data = mysql_query("SELECT * FROM tbl_messages INNER JOIN tbl_users ON tbl_messages.from_user = tbl_users.id WHERE tbl_messages.to_user = $who")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
echo "From:" . $info['id'];
echo "to:" . $info['id'];
}
one good way to do this is to say
SELECT tbl_messages.id as msgID, tbl_users.id as usrID, * FROM tbl_messages INNER JOIN tbl_users ON tbl_messages.from_user = tbl_users.id WHERE tbl_messages.to_user = $who
Then you will reference the fields with that name
echo "From:" . $info['msgID'];
echo "to:" . $info['usrID'];