How to display largest total first in MySQL? - php

I have a small query that sums the totals of columns, is there a way I can ORDER BY ASC so that the result displays the rows with the biggest total first.
My query is:
select
sum(SeqID0101 = 1) as SeqID0101,
sum(SeqID0102 = 1) as SeqID0102,
sum(SeqID0103 = 1) as SeqID0103,
sum(SeqID0104 = 1) as SeqID0104,
sum(SeqID0105 = 1) as SeqID0105,
sum(SeqID0106 = 1) as SeqID0106,
sum(SeqID0107 = 1) as SeqID0107,
sum(SeqID0108 = 1) as SeqID0108,
sum(SeqID0109 = 1) as SeqID0109,
sum(SeqID0110 = 1) as SeqID0110
from
PH001_Hist
EDIT
Hi and thanks for your replies.
I am using the code below to produce tow columns, 1 with the name of the field, 2 with the data content. This works as I require. But when the query sums the content of the fields I need to order the result to display the largest field content first.
Example:
Fieldname FieldData
SEQID0101 - 8
SeqID0108 - 6
SeqID0103 - 2
and so no.
$row = mysql_fetch_assoc($FailedList);
echo '<table>';
foreach ($row as $k => $v)
echo '<tr><td>'.$k.'</td><td >'.$v.'</td></tr>';
echo '</table>';
I just can't get the code right to produce the require result.
Any help would be great.

Try that:
ORDER BY GREATEST(SeqID0101,SeqID0102,SeqID0103,SeqID0104 , .....) DESC

Related

Issue sorting inside while loop

I have a strange issue happening. I've got a table where I want to order the number of times a product was sold. I'll post the query, but the issue is inside the while loop.
Query:
$cat = $db->query("SELECT *, COUNT(id_produto) as quantos FROM produtos p JOIN pedidos m ON p.id_prod = m.id_produto GROUP BY id_produto ORDER BY quantos +0 DESC");
$cat->execute();
Now the loop:
while($res_cat = $cat->fetch(PDO::FETCH_ASSOC)){
$quantidade_ok = $res_cat['quantos'] * $res_cat['qtde'];
$quanti = array($quantidade_ok);
rsort($quanti);
foreach($quanti as $ord){
echo $ord."<br>";
}
The output is:
40
50
4
1
3
2
10
But I want it to be:
50
40
10
4
3
2
1
I'll be happy for any help.
You're sorting within a loop (so your sorting already happened), and you're sorting an array with just 1 value $quanti, so your sort does nothing.
You have 2 ways to approach this properly: edit your query to actually sort how you wish, or sort the PHP array before looping it.
Option 1: Edit your query
Based on your code it seems clear that you wish to sort by the product of quantos times qtde. So you can simply edit your query as follows:
SELECT *, COUNT(id_produto) as quantos
FROM produtos p JOIN pedidos m ON p.id_prod = m.id_produto
GROUP BY id_produto
ORDER BY (quantos*qtde) DESC
Option 2: Sort via PHP
If you prefer to sort via PHP as you don't want to change your query, you can simply populate a temporary array, the product of quantos times qtde as key and then use krsort to sort the array.
In code:
$array = [];
while ($res_cat = $cat->fetch(PDO::FETCH_ASSOC)) {
$key = $res_cat['quantos'] * $res_cat['qtde'];
$array[$key] = $res_cat;
}
krsort($array);
foreach ($array as $ord => $res_cat) {
echo $ord."<br>";
}
You overwrite $quanti each time so it always has a single value.
Try this:
$quanti = [];
while($res_cat = $cat->fetch(PDO::FETCH_ASSOC)) {
$quantidade_ok = $res_cat['quantos'] * $res_cat['qtde'];
$quanti[] = $quantidade_ok;
}
rsort($quanti);
foreach($quanti as $ord){
echo $ord."<br>";
}

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"
}

Unique value count of comma separated field (PHP - MySQL)

I have mysql table that looks like this:
id place interest
1 place1 a,b,c
2 place2 c,d,e
3 place1 a,e
4 place2 f
5 place2 f
6 place3 g,h
I need to get unique "place" and "interest" values sorted as per the count.
So, the output for "place" would be
place2(3)
place1(2)
place3(1)
So, the output for "interest" would be
a(2)
c(2)
e(2)
f(2)
b(1)
d(1)
g(1)
h(1)
is there a way to do this in PHP-Mysql?
So, far I have been able to get simple column data
SELECT place,
COUNT( * ) AS num
FROM testtab
GROUP BY place
ORDER BY COUNT( * ) DESC
As mysql is not able to hold arrays, its better to build a new table like this:
interest_id interest_name
1 a
2 b
and another one to keep the relations:
pk id interest_id
1 1 1
2 1 2
which this id is the id of the records in your main table.
With having this, you can easily use:
select count(*) from THIRD_TABLE where id = YOUR_ID
You can do this.
$place = array();
$interests = array();
foreach($rows as $row){
if (!isset($place[$row["place"]])){
$place[$row["place"]] = 0;
}
$place[$row["place"]]++;
$ints = explode(",", $row["interests"]);
foreach($ints as $int){
if (!isset($interests[$int])){
$interests[$int] = 0;
}
$interests[$int]++;
}
}
This will give you the two arrays keyed off of the relevant field with the value being the count. If this is going to be a common action in your application it would make more sense to normalize your data as suggested by AliBZ.
This is for the first result you need
SELECT place,COUNT(interest)
FROM `testtab`
GROUP by place
ORDER BY COUNT(interest) desc
can do this :
$inst_row = '';
foreach($rows as $row){
$inst_row .= $row['interests'];
}
$inst_values = explode(',', $inst_row);
$inst_count = array_count_values($inst_values);
// $inst_count will return you count as you want ,print_r it and format it accordingly

PHP SUM function

I have a table like following:
id q_id value
------------------------
1 2 5
2 2 NULL
3 2 5
4 2 NULL
5 4 2
6 4 NULL
7 4 2
8 4 NULL
What I want is to get the sum of (for example) all value where q_id = 2
$sq = mysql_query("SELECT SUM(value) AS sum FROM table WHERE q_id = 2)or die(mysql_error());
while($row = mysql_fetch_array($sq)){
$sum = $row['sum'];
}
echo $sum."<br>";
But I'm getting
5
5
But what I want is the sum of the value and expecting 10 instead.
Thank you for helping.
If you're going to loop over the result set anyway, why not just use
SELECT value FROM table WHERE q_id=2
then sum up those values using the while loop? Something like:
while($row = mysql_fetch_array($sq)) {
    $sum += $row['value'];
}
echo $sum."<br>";
Edit: also, as Jason McCreary said above, you should look into an alternate method of querying the database. I would suggest searching php.net for "PDO", which is very easy to use.
We can directly sum in the query like
SELECT 5+6 AS addition
Give it a try... You are displaying value, there was missing quote in your code.
$sq = mysql_query("SELECT SUM(value) AS sum FROM `table` WHERE `q_id` = '2'")or die(mysql_error());
while($row = mysql_fetch_assoc($sq))
{
$sum = $row["sum"];
}
echo $sum . "<br>";
$sq="SELECT value FROM table WHERE q_id='".$am."'";
$result=mysqli_query($link,$sq);
while($row=mysqli_fetch_assoc($result)) {
$sum += $row['value'];
}
echo "<p>Sum: ".$sum."</p><br>";
//$am ='2';
//$link -- connection to the data base
Please put $am ='2'; before the select statement and also make sure you have connected to the data base using $link
You will get the total sum according to the value of q_id
I have tested the code and works fine.
You need to add a GROUP BY to your query. Add the following to the end
GROUP BY q_id

How to retrieve first 2 results from mysql array without querying again?

Each page lists all the coupons available for a specific retailer. I query the database for all the coupon codes in the header since I count the number of rows returned and use that info in the meta title of the page. I now also want to display the titles of the first 2 coupons in the array. How would I go about extracting the first 2 results from the array without querying the database again?
This is what I have so far:
$retailer_coupons = "select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category from tblCoupons C,tblMerchants M where C.merchantid=M.merchantid and C.begin < ".mktime()." and C.expire > ".mktime()." and C.merchantid=".$merchantid." and M.display='1' and C.user_submitted='' order by C.custom_order desc, C.coupon desc";
$retailer_coupons_result = mysql_query($retailer_coupons) or die(mysql_error());
$count_coupons=mysql_num_rows($retailer_coupons_result);
$meta_title = ''.$name.' Coupon Codes ('.$count_coupons.' coupons available)';
Suppose I have 3 records in my table. If I execute below query, I will get 2 results however the count(*) will give me 3 as output
SELECT count(*) FROM temp.maxID limit 2
In your case it will be
$retailer_coupons =
"select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category
from tblCoupons C,tblMerchants M
where C.merchantid=M.merchantid
and C.begin < ".mktime()." and C.expire > ".mktime()."
and C.merchantid=".$merchantid." and M.display='1'
and C.user_submitted=''
order by C.custom_order desc, C.coupon desc
limit 2";
limit 2 will do the magic... Cheers!!!
Good Luck!!!
Something like this:
$res = mysql_fetch_assoc($retailer_coupons_result);
$i = 0;
while ($i < 2){
echo $res[$i]['label']."\n";
$i++;
}

Categories