I have the following table in my database
click to view
I'm looking to find everyone whose user_group is "member", then put their ratings in an array and print their names in descending order based on their rating.
So in the example given, it would output ted67945<br>ted67942.
I currently have this code
function getInfo($info, $given_username) { // This is only used to get the rating of the given user
require($_SERVER["DOCUMENT_ROOT"]."/movies/scripts/db.php");
$result = mysqli_query($conn, "SELECT ".$info." FROM members WHERE username='$given_username'");
while ($row = mysqli_fetch_array($result)) { // for each member
return $row[$info];
}
}
$result = mysqli_query($conn, "SELECT username FROM members WHERE user_group='member'") or die(mysql_error());
$ratings = Array();
while ($row = mysqli_fetch_array($result)) { // for each member
$name = $row['username'];
if(!empty($name)) {
array_push($ratings, getInfo("rating", $name)); // This puts all people's ratings in group "member", into an array
}
}
rsort($ratings);
foreach($ratings as $x) {
echo $x . "<br>";
}
This, obviously, outputs the numbers. How would I use this to output the names based on their rating?
Why can't you just use ORDER BY in your SQL request?
SELECT username FROM members WHERE user_group='member' ORDER BY rating DESC;
This will sort your data by rating in descending order. See more.
Related
I have created an array, it is used to fetch data from MySQL server.
$ids = array(249853, 245549, 249851, 245552, 245551, 249854, 245550, 282445, 261747, 249852, 222398, 248072, 248390, 272473, 219212, 234140, 249815, 241089, 271940, 274940);
$sorted_ids = implode($ids, ",");
Fetched data using $sorted_ids which is ID to retrieve, but it is retrieved data by ID ascending order
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids})";
$result = mysqli_query($connection, $sql);
I have tried using == but it is showing only indexes matched records others not.
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
if( $ids[$i] == $row['ID'] ) {
echo $row['ID']."<br>";
$i++;
}
}
It is showing records if both indexes matched not other records.
How can I display records by $ids array list ?
Easiest way to do what you want is to the order it within your SQL
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids}) ORDER BY FIELD(id, {$sorted_ids})";
Should do the trick
I'm trying to sort different users 'points' by descending order (highest first). But at the moment the query is being returned in order of the user's ID (order they appear in the database). I'm not sure what is wrong with my code?
The user can be in multiple leagues, so it first queries to see what leagues that the particular user is in. With the league IDs, I query to see what users are in each of the leagues. Then I query what each users total points are within that league. Ultimately, I want to get the rank of the user for each league but at the moment the query to order by the points is not working.
The image shows how the points are coming out. '1635' is the users points that is logged in. For the first league, I'm trying to get 'rank 2' displayed.
// SQL query to see what leagues user is in
$query = mysqli_query($con, "SELECT * FROM UserLeague WHERE UserID='$userid'");
$num = mysqli_num_rows($query);
if($num == 0) {
echo 'You are not in any leagues';
return;
} else {
echo '<div class="pleague-table">';
echo '<div class="pleague-table-header">';
echo '<p>PRIVATE LEAGUE</p>';
echo '<p>CURRENT RANK</p>';
echo '</div>';
}
while($leagueid = mysqli_fetch_assoc($query)) {
$lid = $leagueid['LeagueID'];
// Get all league info that user is in
$query2 = mysqli_query($con, "SELECT * FROM League WHERE LeagueID='$lid'");
// Get all users that is in each league
$queryposition = mysqli_query($con, "SELECT UserID FROM UserLeague WHERE LeagueID='$lid'");
while($getpoints = mysqli_fetch_assoc($queryposition)) {
$uid = $getpoints['UserID'];
// Get each users points in each league
$querypoints = mysqli_query($con, "SELECT * FROM Points WHERE UserID='$uid' ORDER BY total DESC");
while($row = mysqli_fetch_assoc($querypoints)) {
echo $row['total']. '</br>';
}
}
while($leaguename = mysqli_fetch_assoc($query2)) {
echo '<div class="league-link">';
echo $leaguename['Name'];
echo 'Options';
echo '</div>';
}
}
'''
You are trying to combine 2 tables: UserLeague and Points to select users from UserLeague and order them by Points. For such cases there is JOIN syntax in SQL:
SELECT Points.*
FROM Points
RIGHT JOIN UserLeague ON Points.UserID=UserLeague.UserID
WHERE UserLeague.LeagueID=?
ORDER BY Points.total DESC
I'm working in PHP and MySQL to create and list a membership directory. I have three tables - company, contact and branch. Companies have Contact people, and some but not all companies have Branches, which also have Contact people. I am using LEFT JOIN in my first query to connect the contact people to their respective company, and loading the results into an array, which works using the following code:
// Retrieve all the data from the "company" table
$query = "SELECT * FROM company LEFT JOIN contact ON company.company_id = contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, contact.cont_rank";
$result = mysql_query($query)
or die(mysql_error());
// Build the $company_array
$company_array = array();
while($row = mysql_fetch_assoc($result)) {
$company_array[] = $row;
}
Now I am trying to figure out how to run a second query, which needs to select from my branch table all branches whose company_id match the company_id stored in my above array: $company_array. I then want to store the results of the second query into a second array called $branch_array. I have tried this:
// Retrieve all the matching data from the "branch" table
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
}
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
But this does not seem to work... Can anyone give me an example of how to do this? The query needs to run so that it checks each different company_id in my $company_array for a match in the branch table - hopefully the question makes sense. Thanks.
i think your while should be inside your foreach statement so that your $branch_array can be filled with results of all company_id values, not only the last one :
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
}
I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike
I am writing a web application in PHP which will store employee data and generate employee ID cards to PDF. I am using FPDF for creation of PDFs and that works fine. I am having a problem with showing results from MySQL database.
I have to generate PDF with 4 employee ID cards and I am not sure how to get them from the database. So far I am using LIMIT option in the query to get only 4 results and i will have an if statement based on mysql.php?id=1 id which will define the limit. It is a little messy but there are not going to be more than 80 employees.
This is my code:
$id = $_GET['id'];
if ($id == 1) {
$limit_start = 0;
$limit_end = 4;
}
$result=mysql_query("SELECT users.tajemnik, users.dateCreated, users.showmeID,
users.workerName, users.dateCreated, users.workerPlace, users.workerSID, uploads.userID, uploads.data, uploads.filetype
FROM users INNER JOIN uploads ON users.showmeID = uploads.userID ORDER BY workerName DESC LIMIT $limit_start, $limit_end") or die (mysql_error());
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
while($row = mysql_fetch_array($result)){
$workerName = $row["workerName"];
$workerPlace = $row["workerPlace"];
$workerSID = $row["workerSID"];
$tajemnik = $row["tajemnik"];
$showmeID = $row["showmeID"];
$mysqldatetime = strtotime($row['dateCreated']);
$image = $row["data"];
$phpdatetime = date("d.m.Y",$mysqldatetime);
}
This will get me the first result from the query. I need to get information from all 4 rows and have them stored in variables like $workerName1, $workerName2 etc. I hope it makes sense what I am trying to do.
Thank you for your replies!
V.
I need to get variables like $workerName1, $workerName2 etc
Nope, you don't.
You actually need an array.
So, first, get yourself a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
$sql = "SELECT users.tajemnik, users.dateCreated, users.showmeID, users.workerName,
users.dateCreated, users.workerPlace, users.workerSID, uploads.userID,
uploads.data, uploads.filetype
FROM users
INNER JOIN uploads ON users.showmeID = uploads.userID
ORDER BY workerName DESC LIMIT $limit_start, $limit_end";
$data = sqlArr($sql);
Now you have all your data in the $data array.
So, you can loop over it or access single values like
echo $data[0]['tajemnik'];
or
foreach($data as $row) {
//do whatever you want with database row
echo $row['tajemnik'];
}