Php number each query result - php

I am making a leaderboard, I want to number it like 1st place 2nd place etc in a html table field.
How to I number each row of information coming out?
Something like
$result + 1 ?
My query
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
}
Thanks.

You can sort through the query results using:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$rows = mysqli_num_rows($result);
for($x = 1; $x <= $rows; $x++) {
$row = mysqli_fetch_array($result);
echo "#{$x} " . $row['bank'];
}
This will start counting down, showing "#1... #2... #3..." etc. You can also do this with your while loop:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$x = 1;
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
echo "#{$x} " . $bank;
$x++;
}

With query itself you can build the result, I think this is what u needed. Not sure
SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900
In php
$result = mysqli_query($con,"SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
while($row = mysqli_fetch_array($result)) {
$rank = $row['rank'];
$bank = $row['Bank'];
}

Related

Accessing SQL Aliases with PHP

This code works to give me what I want in my phpMyAdmin server:
SET #row_number = 0;
SELECT salesperson, units, profit, (#row_number:=#row_number + 1) AS position
FROM sales AS t ORDER BY profit DESC;
The problem happens when I transfer this to php:
<?php
$sql = "SELECT salesperson, units, profit, (#row_number:=#row_number + 1) AS position\n"
. "FROM sales AS t ORDER BY profit DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result))
echo $row['salesperson'] . " " . $row['units'] . " " . $row['profit'] .$row['position'] . "<br>";
}
It outputs the first three rows but not the fourth. The alias created with SQL.
First of all, you choose not exactly the best way to debug your output. Stringifying $row['position'] directly (by piping it into echo) hides a lot of useful info that you would be able to find otherwise.
Second, the query in your second snippet misses actually setting up that variable, like this:
$sql = <<<QUERY
SELECT salesperson, units, profit,
(#row_number:=#row_number + 1) AS position
FROM sales AS t, (SELECT #row_number := 0) AS r
ORDER BY profit DESC
QUERY;
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result)) {
echo "$row[salesperson] $row[units] $row[profit] $row[position]<br>";
}
}
Additionally, in the latest version of MySQL (8.0+) window functions are finally supported which avoids the use of # session variables. Doing so you can also add row numbers by group with PARTITION BY clause:
SELECT salesperson
, units
, profit
, ROW_NUMBER() OVER(ORDER BY profit DESC) AS `overall_position`
, ROW_NUMBER() OVER(PARTITION BY salesperson
ORDER BY profit DESC) AS `salesperson_position`
FROM sales
ORDER BY profit DESC

Selecting only amount with values greater than 0 in sql

I have this table
The table contains amount with values that has both negative and positive signs. I was able to fetched the sum of positive amount but after the sumation I have zero values which I don't want to show - it fetched all values.
Objective: fetch sum of amount and return amount with no zero values.
What I tried so far
$ques = "select * from company";
$checks22y = sqlsrv_query($conn, $ques);
$row22y = sqlsrv_fetch_array($checks22y, SQLSRV_FETCH_ASSOC);
$daty = $row22y['BRSES_DATE']->format('Y-m-d H:m:i');
$com = $row22y['branch'];
$query = "SELECT distinct ".$limitresult." Member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,
Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,
nType,Group_Code FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND
Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No
INNER JOIN Customer ON Member.Branch = Customer.Branch ".$branchid." AND Member.Cust_No = Customer.Cust_No ".$accnos." WHERE
CUSTACC.Exp_Date < '$daty' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') ";
$check = sqlsrv_query($conn, $query);
$i = 1;
while($rows = #sqlsrv_fetch_array( $check, SQLSRV_FETCH_ASSOC)) {
$ac = $rows['Ac_NO'];
$br = $rows['Branch'];
//Second sub query
$get ="select ac_no, gl_no, SUM(amount) as OutBalance,MAX(Batch_Date) AS Last_Trx2 from memtrans where gl_no like '2001%'
and ac_no='$ac' group by ac_no, gl_no HAVING SUM(amount) > 0
";
$check2 = sqlsrv_query($conn, $get);
$rowb = sqlsrv_fetch_array( $check2, SQLSRV_FETCH_ASSOC);
//Third sub query, OD history
$od = "select od_limit from custacc where ac_no='$ac' and od_limit > '0'";
$odc = sqlsrv_query($conn, $od);
$rowbo = sqlsrv_fetch_array( $odc, SQLSRV_FETCH_ASSOC);
}
The outcome
If you look at the Outstanding Balance you will see zero values appearing.
The secon sub query is where the fetching of Outstanding Balance took place.
Just solved it.
Here is the query I later used:
SELECT distinct ".$limitresult." member.Branch,Member.GL_No,Member.Ac_NO,Member.BRANCH+Member.GL_NO+Member.AC_NO
AS BRGLAC,Customer.Cust_No,Customer.Name,Group_Name,ID_CARD,Subgroup as subgroup2,Cust_Type,Cust_Sex,Cust_Cat,Area_Code,Cust_Type,Dobirth,Address,Ref_No,Bank_VNO,Cust_Ca2,nType,Group_Code, SUM(memtrans.amount) as OutBalance,MAX(memtrans.Batch_Date) AS Last_Trx2,company.BRSES_DATE, company.branch, CustACC.od_limit FROM Member INNER JOIN CUSTACC ON Member.Branch = CustAcc.Branch AND Member.GL_NO = CustACC.GL_No AND Member.AC_NO = CustACC.AC_No INNER JOIN Customer ON Member.Branch = Customer.Branch AND Member.Cust_No = Customer.Cust_No INNER JOIN memtrans ON memtrans.ac_no = member.ac_no INNER JOIN company ON company.branch = member.branch ".$branchid." ".$accnos." WHERE CUSTACC.Exp_Date < company.BRSES_DATE AND CUSTACC.od_limit > '0.00' AND MEMBER.Gl_NO IN (SELECT Coa.GL_NO FROM Coa WHERE Product = 'S' ) AND cust_type IN ('IND','GRP','MEM') group by memtrans.ac_no, memtrans.gl_no,company.branch, member.branch, member.gl_no,Member.ac_no,
Customer.cust_no, Customer.name, Customer.group_name,Customer.id_card,Customer.subgroup,Customer.cust_type,
Customer.cust_sex, Customer.cust_cat,Customer.area_code,Customer.dobirth,Customer.address,Customer.ref_no, Customer.Bank_VNO,Customer.cust_ca2,Customer.ntype,Customer.group_code,company.BRSES_DATE,CUSTACC.od_limit HAVING SUM(memtrans.amount) > 0)
Thanks guys. From a grateful heart.

Calculate SUM in PHP

<?php
$today=date('Y-m-d');
$sorgu = mysqli_query($conn, "SELECT * FROM urun");
while ($sira = mysqli_fetch_array($sorgu)) {
$urun = $sira['urun'];
$query = mysqli_query($conn, "SELECT product_name, birim, SUM(quantity) FROM
product WHERE product_name = '$urun' AND quantity != '0' AND quantity > '0'
AND grup!='uygulama' AND skt > '$today' GROUP BY product_name, birim ");
while ($row = mysqli_fetch_array($query)){
if ($row['2'] <= $sira['minstok']) {
echo count($row['0']);
} } } ?>
This code belongs to a table which has a notification system. I want the notification part increase when the line number increases in that table but it turns 11111111... , So how can I make the code give me sum?
Incidentally, everything up to while ($row... can be rewritten as follows:
SELECT p.product_name
, p.birim
, SUM(p.quantity) total
FROM urun u
JOIN product p
ON p.product_name = u.urun
AND p.quantity > 0
AND p.grup != 'uygulama'
AND p.skt > CURDATE()
GROUP
BY p.product_name
, p.birim;

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

How do I get the result into a variable MYSQL

I have the following PHP script. How do I get the correct results. Each query should only return a number. I need to get rank in this case. I was also wondering how to combine those two queries into one statement.
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$rowWorld = mysql_fetch_row($resultWorld);
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$rowCountry = mysql_fetch_row($resultCountry);
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
If I type the queries individually into MYSQl I get the correct answers. But the echo produces
[{"WorldRanking":null,"CountryRanking":null}]
It should be something like
[{"WorldRanking":"4","CountryRanking":"1"}]
I think I need to get the value of rank but I do not know how.
try your code like this, but I don't know this code correct or not:
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
while ($rowWorld = mysql_fetch_row($resultWorld)){
$value1 = $rowWorld['filedname1'];
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
while($rowCountry = mysql_fetch_row($resultCountry)){
$value2 = $rowWorld['filedname2'];
}
$arr[] = array("WorldRanking" => $value1, "CountryRanking" => $value2);
print_r($arr);
}
<?php
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$no_of_results_in_resultWorld = mysql_num_rows($resultWorld);
if($no_of_results_in_resultWorld > 0){
$rowWorld = mysql_fetch_row($resultWorld);
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$no_of_results_in_resultCountry = mysql_num_rows($resultCountry);
if($no_of_results_in_resultCountry > 0){
$rowCountry = mysql_fetch_row($resultCountry);
}
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
check whether it is returning results or not.

Categories