Get information from MySql Query and put it in PHP array - php

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!

Related

Sum fields from different tables per userID

Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}
You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";
You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial

SQL - Displaying names instead of ID [duplicate]

This question already has answers here:
Select Name instead OF ID in table with ID-Ref Column SQL
(2 answers)
Show Name Instead of ID from Different Table
(2 answers)
Closed 1 year ago.
I have 2 tables
rankID | name
1 | new
2 | learner
3 | experienced
4 | pro
And another with all the user info and passwords and stuff
id | username | rankID
1 | hello | 3
2 | hey | 3
I have come so far so I can display their rank number, but I want to display the rank name. How can I do that? I have tried a lot of things but I'm not so good at sql and the php part of it.
This is the code I use to display the rank number
//Get rankID
$query = "SELECT rankID FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
And to display the rank number:
Rank: <?php echo $rank; ?>
Simple JOIN query :-
"SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'"
And then After:-
$query = "SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
Do:-
$rank = $row['rankID'];
$rank_name = $row['rank_name'];
Rank: <?php echo $rank; ?>
RankName: <?php echo $rank_name; ?>
Or
$rank_data = $row;
Rank: <?php echo $rank_data['rankID']; ?>
RankName: <?php echo $rank_data['rank_name']; ?>
Not:- lot of other possible ways are there which are listed by other programmers in comment and answer as well.
//Get datas
$query = "SELECT rankID, name FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
$rank = $row['name'];
And to display the datas:
Rank: <?php echo $rank; ?>
Name: <?php echo $name; ?>
Hope so this should make a trick for you.
$query = "SELECT rankID FROM users WHERE id = '".$userId."'";
$result = $conn->query($query);
$count = $result->num_rows;
if($count==0)
{
return false;
}
else
{
$rows=[];
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
Please use below code
$query = "SELECT name FROM users as u JOIN rank as r ON r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
Name: <?php echo $name; ?>
When you want to get data from two different table.You need join query.
Here is your query which will solve your proble definitely :
$q="select a.name,b.rankID from rankname as a INNER JOIN user as b
ON a.rankID = b.rankID";
For more know about How to join two tables see this:http://www.tutorialspoint.com/sql/sql-using-joins.htm
Hope this will help you better.
Please try this
//Get rankID
$query = "SELECT r.name as rank_name FROM rank as r inner join users as u on r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo 'Rank: '. $rank;
try this:
//Get rankID
$query = "SELECT rankID, rank.name AS rank_name FROM rank, users WHERE id = '$userId' and users.rankid = rank.rankid";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo $rank;

Ranking list with all the users

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++;
}

PHP/MySQL Update query every 2 column update room change automated

I want to create automated room divisions.
Assumptions :
I have 4 data.
Each room maximum 2 people.
If room is full / reach max "2", 3th people automated insert to the next room.
Here my code. assumption 4 data.
$kuota=2; //Max 2 data in 1 room
while ($row = mysqli_fetch_array($query)) {
$id = $row["id"];
$x=1;
while($x<=$kuota) {
$sql2 = "UPDATE cds SET room=$y WHERE id='$id'";
$query2 = mysqli_query($con, $sql2) or die (mysqli_error($con));
$x++;
}
$y++
}
but it doesn't work.
My code is so ugly :(
I want to get a result like this
name || Room
Michael || 1
Muller || 1
...
Cyntia || 2
Gina || 2
while ($row = mysqli_fetch_assoc($query)) {
$id = $row['id'];
$sql2 = "UPDATE cds AS c1
CROSS JOIN (SELECT room
FROM cds
GROUP BY room
HAVING COUNT(*) < $kuota
ORDER BY room
LIMIT 1) AS c2
SET c1.room = c2.room
WHERE id = $id";
mysqli_query($con, $sql2) or die (mysqli_error($con));
}
The c2 subquery returns the first room that has fewer than $kuota people assigned to it.

PHP/MySQL Select Statement

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)

Categories