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++;
}
Related
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
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'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'
I'm trying to get the total number of product sales in each category, although the database structure being used doesn't really seem to lend itself to this.
I've gotten it to the point where I have the IDs of products (it's own table) in a category (another table) that have only been purchased (still another table). So looping through the category, I choose the IDs in the orders table and try to count the rows. I end up with the item count per item, but any way I try to merge and count them up them doesn't work.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
while($row_active_accounts = mysql_fetch_row($res_active_accounts)){
print_r($row_active_accounts);
}
};
An example that print_r gives for a specific category that only had 3 items sell, but some items sold more than once:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 1 )
This is correct in that three items sold, sold those number of times.
And array_sum doesn't work on this. I can't seem to do anything to get those numbers to add up. I'm trying to count just specific rows and really don't care about the data in them for the final result.
I understand SQL calls within loops are a bad idea, but this is an admin area script that won't be run often.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL ); while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
$int_total = 0;
while($row_active_accounts = mysql_fetch_row($res_active_accounts) {
foreach($row_active_accounts as $i)
$int_total += $i;
}
// Use $int_total for total value
Some like this should do the trick for your if I understand you correctly.
Try this
$query = mysql_query("select distinct(pgroup) from test") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row['pgroup']."=>";
$query1="SELECT count(*),pname FROM `test` where pgroup='$row[pgroup]' group by pname ";
$result1=mysql_query($query1) or die(mysql_error());
$rows1=mysql_num_rows($result1);
while($row_sub=mysql_fetch_array($result1)) {
$query2 = "select * from test where pname = '".$row_sub['pname']."'";
$res2=mysql_query($query2) or die(mysql_error().'errror here');
$row2 = mysql_num_rows($res2);
echo $row_sub['pname']."=".$row2."<br/>";
}
}
I have the following table structure. One table EQUITIES and a table for each row in this table.
EQUITIES table:
id instrument
and tables for every instrument with are all similar to this:
Tables named like EE5367126893 (various names and the names are stored in equities table).
EE5367126893
id chg
EDIT:
My code is BAD. It somehow gets me wrong results and i can't seem to find an error.
<?
//CREATION OF TOP MOVERS
include('connect.php');
$sql = "SELECT * FROM equities";
$result = mysql_query($sql) or die(mysql_error());
$instruments = array();
while ($row = mysql_fetch_array($result)) {
array_push($instruments, $row["instrument"]);
}
$i=0;
foreach($instruments as $instrument) {
$sqlx .= "(SELECT id, chg, vol, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
if ($i<count($instruments)-1){
$sqlx .= " UNION ";
$i++;
}
}
$gsql = $sqlx;
$lsql = $sqlx;
$vsql = $sqlx;
//Gainers
$gsql .= " ORDER BY chg DESC LIMIT 3";
$gresult = mysql_query($gsql) or die(mysql_error());
while ($grow = mysql_fetch_array($gresult)) {
$g[$grow['name']] = $grow['chg'];;
}
print_r($g);
//losers
$lsql .= " ORDER BY chg ASC LIMIT 3";
$lresult = mysql_query($lsql) or die(mysql_error());
while ($lrow = mysql_fetch_array($lresult)) {
$l[$lrow['name']] = $lrow['chg'];;
}
print_r($l);
//most volume
$vsql .= " ORDER BY vol DESC LIMIT 3";
$vresult = mysql_query($vsql) or die(mysql_error());
while ($vrow = mysql_fetch_array($vresult)) {
$v[$vrow['name']] = $vrow['vol'];;
}
print_r($v);
?>
It got me results:
Array
(
[LV0057869] => 0.68
[EE310054309] => 0.00
[EE3100034553] => -5.03
)
Array
(
[LV0054359] => -0.84
[LT0000543337] => -3.83
[LT00453127375] => -4.03
)
Array
(
[EE310054334653] => 791
[EE3100003609] => 58538
[LT000543337] => 33240
)
Its pretty obvious that I'm not getting the the highest, lowest or values with most vol (as -0.84>-5.03).It looks like random values got locked with this query. Where's the catch? Im pretty sure theres something bad with my sql query...
You can add name to select
SELECT id, chg, 'table_name or instrument_name' as inst_name from ...
Example:
$sqlx .= "(SELECT id, chg, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
It seems that vol has got VARCHAR type and rows are sorted by chars not by integers.
Could you provide your table scheme?