Ranking/numbering in php - php

I tried to achieve a method in which I create a scoreboard (while loop) and order the fetched results by a certain numeric field (points). But what I need to achieve is like the following
rank----username--point
1st------test-----------3200
2nd-----test2---------1200
etc.. I paginate my results and limit 25 results per page. I tried a while loop in the following way
while($row = mysql_fetch_array($query) || $i<=$totalnumberofrows ){
echo out the results
$i++
}
What this does is number from 1 to 25 perfectly, but on the other hand, on page 2 it numbers again from 1-25.
Is there a trick to achieve what I need to achieve?
I.e. continuous numbering from 1 to (total number of rows) even when paginated.

What you're looking for is the MySQL LIMIT statement. For example, the following query would return entry 0-24 (so, the first 25 entries in your database):
SELECT * FROM entries ORDER BY `points` LIMIT 0, 25
Say that you want to fetch the second page (the next 25 entries), you can do:
SELECT * FROM entries ORDER BY `points` LIMIT 25, 25
Most important thing to note here is that the first argument is the row where it should start, and the second argument is not the last row, but the total amount of rows it should return.
To determine the starting point, simply do (($page_number - 1) * 25), assuming your first page is numbered 1. You could for example do the following:
<?php
$start = (($page_number - 1) * 25);
$query = "SELECT * FROM entries ORDER BY `points` LIMIT {$start}, 25";
// ... rest of your code goes here ...
?>

just add 25 to the number for each page,
for the second page (in my example) - add 25
for the third page - add 50
etc...
$page = 2;
while($row = mysql_fetch_array($query) || $i<=$totalnumberofrows ){
echo out the results
echo (($page-1)*$totalnumberofrows)+$i;
$i++
}

If you know the page number and the offset you should be able to do the following
$rank = $offset * $page_number;

Related

Get the minimum and maximum number in PHP from DB

I'm making a PHP code for showing data of my weather station.
I have a DB in MySQL with 5 columns.
This is my actual code:
<?php
$conexion=mysqli_connect('localhost','dbone','root','dbdata');
?>
<?php
$sql="SELECT * from Sensor ORDER BY id DESC LIMIT 1";
$result=mysqli_query($conexion,$sql);
date_default_timezone_set("Europe/Warsaw");
$calpres=57;
$caltemp=0;
$calhumi=0;
while($mostrar=mysqli_fetch_array($result)){
?>
<?php
?>
|esta=c00m000e00|data=<?php echo date("d-m-Y H:i:s"); ?>|temp=<?php echo $mostrar['value1'] - $caltemp ?>|hum=<?php echo $mostrar['value2'] ?>|pres=<?php echo $mostrar['value3'] + $calpres ?>
<?php
}
?>
The actual result is:
|esta=c00m000e00|data=24-01-2021 19:42:10|temp=10.71|hum=58.20|pres=1016.12
Value1 is the column that includes the temperature. I would like to show the maximum and minimum temperature, but I don't know how to do it.
Thank you very much!
You could use SQL MAX() and MIN() functions.
Something like SELECT MAX(value1) FROM Sensor
Either run 2 queries (one for min and one for max) like this:
(if your column name is temp)
SELECT * from Sensor ORDER BY temp DESC LIMIT 1
SELECT * from Sensor ORDER BY temp ASC LIMIT 1
and the take the first and only rows from them.
A little bit cleaner way is to take all the data you need, ordered by temp, (no LIMIT at the end)
SELECT * from Sensor ORDER BY temp DESC
fetch it in an array, and get the first tempArray[0] and the last tempArray[count(tempArray)-1] - values, they will containt min and max rows.
$result = mysql_query("SELECT * from Sensor ORDER BY temp DESC");
$sensorArray = []
while( $row = mysql_fetch_assoc( $result)){
$sensorArray[] = $row;
}
$max = $sensorArray[0];
$min = $sensorArray[count($sensorArray)-1];

How to paginate sql query result?

I have some PHP code, which returns all records from my database. I need 10 results on each page. How to paginate the results? Dunno how to write a piece of code responsible for displaying page numbers...
<?php
$query = $link->query("SELECT * FROM news WHERE category='rhythmix' ORDER BY subject DESC");
while($output = $query->fetch_assoc()){
$text = $output['news'];
$text = str_replace('[video]','<div class="video-container">',$text);
$text = str_replace('[/video]','</div>',$text);
$text = str_replace('[media]','<center>',$text);
$text = str_replace('[/media]','</center>',$text);
$embera = new \Embera\Embera();
echo $embera->autoEmbed($text);
}
?>
Add LIMIT to your query in this way:
SELECT *
FROM news
WHERE category='rhythmix'
ORDER BY subject DESC
LIMIT 0, 10;
The first number (0) is the start position on the resulset and the second one (10) is how many results you want to show (the offset).
To show the second page:
...LIMIT 10, 10
If you always want to show 10 results you just need to to add 10 to the first number of the LIMIT.
Change your query to read
$query = $link->query("SELECT * FROM news WHERE category='rhythmix' ORDER BY subject DESC LIMIT 0, 10");
To display the first 10 rows. The next set of 10 rows can be shown using
...LIMIT 10, 10");
and so on. . .

Getting a specific value from my database with an operator

I'm trying to give my users a rank based on the amount of posts they posted. I made a database containing a rankName row with "beginner, novice, itermediate,... to master" and a minimum row with some numbers. I tried to compare the amount of posts ($qtyPosts) with the minimum rows.
For example: When a user has 9 posts, he gets the rank Novice (which has a minimum of 5 posts).
This is the code i wrote for that.
PHP code
// calculate number of posts from user
$rowsPosts = $user->getQuantityOfPosts($userID);
$qtyPosts = 0;
foreach ($rowsPosts as $q) {
$qtyPosts++;
}
//status
$conn = db::getInstance();
$rank = "";
$statementRank = $conn->prepare("SELECT * FROM rank WHERE rank.minimum >= $qtyPosts");
$statementRank->execute();
while($row = $statementRank->fetch(PDO::FETCH_ASSOC) ){
$rank = $row['rankName'];
}
HTML code
<h3>Status: <?php echo $rank; ?></h3>
However, It doesn't post the right rank, instead it posts the latest one, "master". Anyone any idea?
Consider your WHERE clause:
WHERE rank.minimum >= $qtyPosts
If the user is at the lowest rank, then all ranks will be >= that user's post count.
You can keep the same logic, but simply add an order and limit. Something like this:
WHERE rank.minimum >= $qtyPosts ORDER BY rank.minimum LIMIT 1
This would sort the ranks from lowest to highest and just select the first one.
I guess you should have a maximum column as well in the table and change the query to
SELECT * FROM rank WHERE rank.minimum >= $qtyPosts AND rank.maximum < $qtyPosts
Since according to your current post, you'll get all the ranks with $qtyPosts > the minimun number.

PHP How do you create an increasing number array?

as the title says i am trying to create an increasing numbers array for example:
I have a number 30 and i want to create an array out of it like
$numbers = array(6,12,18,24,30);
// then extract data from mysql
foreach( $numbers as $LIMITNUMBER ){
$query = "SELECT * FROM table WHERE id=id ORDER BY ASC LIMIT 0,".$LIMITNUMBER;
}
The 30 number above could be any number 100 or 200 but it always divides by 6 so the array first value has to be 6 and then +6 addition to the previous value.
The easiest way to do this would be to use a function implementing PHP 'range'.
Here's an example based on your question:
function incrementToMax($max) {
foreach (range(6, $max, 6) as $currentMax) {
$query = "SELECT * FROM table WHERE id=id ORDER BY ASC LIMIT 0,".$currentMax;
}
}
Example usage:
incrementToMax(60);

PHP: Mysql limit range numbers

I would like get number of records in a table then divide them by 4, after dividing them by 4 i want to create sql statements with limit ranges based on my result. For example I have a table with 8 records I divide by 4, I will create 2 sql statements with a limit range like limit 0,4 and limit 4,8
Final results will look like
Select * from prop where id=123 LIMIT 0,4
Select * from prop where id=123 LIMIT 4,8
My approach was to have for loop which will count the number of sql statements to be made.
Then in the loop: first circle 0-4 and second will be 4-8
Am struggling on the limit 0-4 and limit 4-8
PHP script
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$results_query_1 = mysql_query($query_1);
while($row_query_1 = mysql_fetch_array($results_query_1))
{
$cnt = $row_query_1['Total'];
}
echo $cnt;
echo "<br>";
$num_grps = 0;
if ($cnt % 4 == 0 )
{
echo $num_grps = $cnt / 4 ;
}
$count_chk= $num_grps * 4;
for ($i=1;$i<=$num_grps;$i++)
{
//for loop for range
for()
{
$range = '0,4';
echo "SELECT prop_ref from prop limit".$range;
}
}
Either you've not understood the problem or haven't explained it very well.
The most immediate problem here is that you have misunderstood the syntax for the LIMIT clause. The first argument specifies the offset to start at and the second defines the number of rows to return, hence LIMIT 4,8 will return 8 rows (assuming there are 12 or more rows in the dataset).
The next issue is that you've not said if the results need to be reproducible - e.g. if you have rows with primary keys 1 and 2, should these always be returned in the same query. In the absence of an explicit ORDER BY clause, the rows will be returned based on the order in which they are found by the query.
The next issue is that you've not explained how you want to deal with the last case when the total number of rows is not an even multiple of 4.
The code you've provided counts the number of rows where ref = 'SB2004' but then creates queries which are not filtered - why?
The code you've provided does not change the limit in the queries - why?
The next issue is that there is never a good reason for running SELECT queries inside a loop like this. You didn't exlpain what you intend doing with the select queries. But based on the subsequent update....
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$cnt = mysql_fetch_assoc(mysql_query($query_1));
$blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);
$qry2="SELECT * FROM prop where ref='SB2004' ORDER BY primary_key";
$res=mysql_fetch_assoc($qry2);
for ($x=0; $x<$blocks; $x++) {
print "<div>\n$block<br />\n";
for ($y=0; $y<4; $y++) {
print implode(",", #mysql_fetch_assoc($res)). "\n";
}
print "</div>\n";
}
It's trivial to refine this further to only issue a single query to the database.
If you really must generate individual SELECTs....
include('connect.php');
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$cnt = mysql_fetch_assoc(mysql_query($query_1));
$blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);
for ($x=0; $x<$blocks; $x++) {
$y=$x*4;
print "SELECT * FROM prop where ref='SB2004'
ORDER BY primary_key LIMIT $y,4<br />\n"
}

Categories