I'm sorting my table which has the id and highscore of the user. This is ordered in descending and I'm passing in the id of the current user to find where he ranks.
I.e: I pass in the ID of the current user and want to echo where he ranks.
select *
from (
select *
from players
order by highscore desc
limit 10
) t
where id = $current_user
I've tried this but no luck with getting the data output in PHP..
$result = $mysqli->query("SELECT COUNT(*) AS rank FROM players WHERE highscore >= (SELECT highscore FROM players WHERE id=$current_user)");
What must I modify to the above to get that users ranking and then echo out his ranking number in PHP? Thanks!
You need to put the data into an array once you query it from the database. Try using mysqli's fetch_assoc like this:
$result = $mysqli->query("SELECT COUNT(*) AS rank FROM players WHERE highscore >= (SELECT highscore FROM players WHERE id=$current_user)");
// Put the data from the query into an array
$row = $result->fetch_assoc();
// Store the rank in a variable named $rank
$rank = $row['rank'];
echo $rank;
Related
I have 2 tables - users and articles.
users:
user_id (int)
name (varchar)
articles:
article_id (int)
user_id (int)
title (varchar)
description (text)
In my application I need to display 20 RANDOM articles on a page.
My query is like this:
SELECT a.title
, a.description
, u.name
FROM articles a
JOIN users u
USING (user_id)
ORDER
BY RAND()
LIMIT 20
A user can have any number of articles in the database.
Now the problem is sometimes out of 20 results, there are like 9-10 articles from one single user.
I want those 20 records on the page to not contain more than 3 (or say 4) articles from a particular user.
Can I achieve this through SQL query. I am using PHP and MySQL.
Thanks for your help.
You could try this?
SELECT * FROM
(
SELECT B.* FROM
(
SELECT A.*, ROW_NUMBER() OVER (PARTITION BY A.USER_ID ORDER BY A.R) USER_ROW_NUMBER
FROM
(
SELECT a.title, a.description, u.name, RND() r FROM articles a
INNER JOIN users u USING (user_id)
) A
) B
WHERE B.USER_ROW_NUMBER<=4
) C
ORDER BY RAND() LIMIT 20
Mmm, intresting I don't think this is possible through a pure sql query.
My best idea would be to have an array of the articles that you'll eventually display query the database and use the standard SELECT * FROM Articles ORDER BY RAND() LIMIT 20
The go through them, making sure that you have indeed got 20 articles and no one has breached the rules of 3/4 per user.
Have another array of users to exclude, perhaps using their user id as an index and value of a count.
As you go through add them to your final array, if you find any user that hits you rule add them to the array.
Keep running the random query, excluding users and articles until you hit your desired amount.
Let me try some code (it's been a while since I did php)
$finalArray = [];
$userArray = [];
while(count($finalArray) < 20) {
$query = "SELECT * FROM Articles ";
if(count($finalArray) > 0) {
$query = $query . " WHERE articleID NOT IN(".$finalArray.")";
$query = $query . " AND userID NOT IN (".$userArray.filter(>4).")";
}
$query = $query . " ORDER BY Rand()";
$result = mysql_query($query);
foreach($row = mysql_fetch_array($result)) {
if(in_array($finalArray,$row) == false) {
$finalArray[] = $row;
}
if(in_array($userArray,$row[userId]) == false) {
$userArray[$row[userId]] = 1;
}
else {
$userArray[$row[userId]] = $userArray[$row[userId]] + 1;
}
}
Im trying to make a custom function for my forum based on php. I have my index landing style page separate to my phpbb forums. I am trying to display the latest registered users username, as part of a statistics type widget for the home page. I have the following code so far:
//Function code
//Total Posts calculation
$result = $mysqli->query("SELECT DISTINCT post_id FROM phpBB_posts
WHERE post_id <= '1'");
$total_posts = $result->num_rows;
//Total topics calculation
$result2 = $mysqli->query("SELECT DISTINCT topic_id FROM phpBB_topics WHERE topic_id <= '1'");
$total_topics = $result2->num_rows;
//Member count calculation
$result3 = $mysqli->query("SELECT DISTINCT user_id FROM phpBB_users WHERE user_id <= '1'");
$total_members = $result3->num_rows;
//Newest member
$result4 = $mysqli->query("SELECT * FROM phpBB_users WHERE group_id <> 6 ORDER BY user_regdate DESC LIMIT 1");
$newestMember = $result4->name;
//End of function
//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);
The "Newest member" section is where i'm having trouble, the rest works as I want, if you have any pointers/criticism i'll gladly take it on board though.
I want to be able to return the value in the username column from the results set i get returned from that query, and print it as the variable $newestMember.
My logic as you can see was to get the list of users, so SELECT * then limit the list to actual users and exclude bots etc so WHERE group_id <> 6. Then sort the list by the registered date ORDER BY user_regdate and then only one row from the full list with DESC LIMIT 1. I've been checking mysql and php documentation and can't work out how to get the value from the returned row/username column (field) and store it as the newestMember variable and print to the page.
Can anyone point me in the right direction please?
Cheers, Jamie
Managed to get it working modifying that code a little, deleted the mysqli->query that prepended the SELECT query and that made it work. What finally worked is as per below if anyone else comes across the same issue. Thanks for the nudge in the right direction CBroe! Needed a fresh pair of eyes and to look at it from a different angle :)
//Newest member
$myresult = ("SELECT * FROM phpBB_users WHERE user_type <> 2 ORDER BY user_regdate DESC LIMIT 1");
if ($result = $mysqli->query($myresult)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
$newestMember = $row[7];
}
/* free result set */
$result->close();
}
//End of function
//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);
Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);
I am trying to display questions, along with the users answer in a specific order, NOT ASC or DESC, but as defined by the "question_order" column.
I have the following tables in a mysql db:
questions (qid, question_text)
answers (aid, uid, answer)
usermeta (userid, question_order)
"questions" table contains the questions
"answers" table contains every users answers to all questions
"usermeta" table contains the sort order for the questions in "question_order".
"question_order" is unique per user and is in the db as a pipe delimited list. (i.e.: 85|41|58|67|21|8|91|62,etc.)
PHP Version 5.3.27
If this entire procedure can be better accomplished using a completely different method, then please let me know.
My PHP ability is limited. With that said, below is what I have at the moment after several hours of playing ...
$sql = "
SELECT
*
FROM
".USERMETA_TABLE."
WHERE
userid = {$userid}
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
$order_array = explode('|', $row['question_order']);
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
// my attempt at sorting the questions. the $order_array
// does not have a unique id so I am kind of lost as to
// how to make this work
usort($myArray, function($order_array, $row) {
return $order_array - $row['qid'];
});
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
while ( $row = $result->fetch_assoc() )
{
$sql = "
SELECT
*
FROM
".ANSWERS_TABLE."
WHERE
uid = {$userid}
AND
qid = ".$row['qid']."
LIMIT
1
";
$result2 = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row2 = $result2->fetch_assoc();
echo ' <p>'.$row['question_text'].'</p>'."\n";
echo ' <p>'.$row2['answer'].'</p>'."\n";
}
Filter out the data when retrieving from db.
Use:- SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
Then in PHP you can use session variables and modify the values accordingly.
If you want to order using ID you can use
SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
this will order in descending order If you want in ascending order use ASC
I went ahead and altered the DB by adding a table to store the question numbers, user sort order, and student user id:
student_id, sort_order, question_id
1 1 8
1 2 2
1 3 97
and then was able to select it all with the following statement:
SELECT q.*
FROM
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = $student_id
...works great.
Thanks to FuzzyTree for his help on this at: How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc
$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)