Distinct and Ordered Results from Average PHP - php

I'm trying to get the averages from the rating column of my table, then display a row in a HTML table for each distinct div_id and its average rating, in descending order. I know this should probably be easy, but I'm having a hard time figuring it out. Any help would be greatly appreciated.
<?php
mysql_connect($db_server, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$result = mysql_query("SELECT * FROM ratings") or die(mysql_error());
while($row = mysql_fetch_object( $result )){
$ad = $row->div_id;
$result2 = mysql_query("SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings WHERE div_id = '" . $ad . "' ORDER BY div_id DESC ") or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )){
$adid = $row2[0];
$count = $row2[2];
$avg = round($row2[1],2);
echo "<tr><td>";
echo $adid;
echo "</td><td>";
echo $avg;
echo "</td></tr>";
}
}
?>

Instead do tow queries, you can use the GROUP BY term in only one query.
SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings GROUP BY div_id ORDER BY div_id DESC
php code
<?php
mysql_connect($db_server, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$result = mysql_query("SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings GROUP BY div_id ORDER BY avg DESC") or die(mysql_error());
while($row = mysql_fetch_array( $result )){
$adid = $row[0];
$count = $row[2];
$avg = round($row[1],2);
echo "<tr><td>" . $adid . "</td><td>" . $avg . "</td></tr>";
}
?>

Perhaps you should try doing this all in one query:
SELECT div_id, avg(rating) AS avgrating, COUNT(*) as cnt
FROM ratings
GROUP BY div_id
ORDER BY avgrating desc;

Related

How to write while loop into another while loop for fetch data from SQL query?

I want to get data from two different queries, so first I get data by writing this code:
$sql = "select DATE_FORMAT(tr_date,'%d/%m/%Y %H:%i:%s') as tr_date,p1,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,tno from rnb_gpl_data where DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i:%s') >= '$s' AND DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i:%s') <= '$e' and did = '$did' order by srno desc limit $offse, $rec_limi";
$retval = mysqli_query($con, $sql);
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
$sqlll = "select * from rnb1_data where DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i') >= '$s' AND DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i') <= '$e' and did = '$did' limit $offse, $rec_limi";
$retval11 = mysqli_query($con, $sqlll);
if(! $retval11 ) {
die('Could not get data: ' . mysqli_error());
}
while($rowww = mysqli_fetch_array($retval11, MYSQL_ASSOC)) {
$bit = $rowww['bitumen_tph'];
$netmixt= $rowww['netmix'];
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
$jv1=$row['p1'];
echo "<tr > ".
"<td class=\"center\">$jv1</td> ".
"<td class=\"center\">$bit</td> ".
"<td class=\"center\">$netmixt</td> ".
}
}
But my netmixt and bit value remain same for all record. Only jv1 value change according to my database record. I want to update all data according to my database table.
In this image first column is jv1 value second is bit and third is netmix.
You can see that bit and netmix value remain same for all rows but actually it differ in database table.

Printing table values in ascending order

I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ

How to pull the last 7 days from mysql database which includes count?

I am querying a table in mysql. At the moment the query works fine and counts the amount of repeated records which are in a table.
$sql = "SELECT COUNT(*) as c FROM toutcome WHERE affID = '" . $_SESSION['affID'] . "' ";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['c'] ;
Now I need to display that same count, but it needs to display only for the last 7 days. I have tried following and it does not works:
$sql = "SELECT COUNT(*) as c FROM toutcome WHERE affID = '" . $_SESSION['affID'] . "' and CompletedDate > DATE_SUB(CURDATE(), INTERVAL 7 DAY) ";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['c'] ;
Any advice would be great.

Show Table Name From Query

I have a SELECT staement where I JOIN 2 separate tables.
$result = mysql_query('SELECT * FROM (SELECT * FROM gslil0009) as table1 UNION SELECT * FROM (SELECT * FROM gslil0028) as table2' . ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
}
How do I print out which table the row came from?
$result = mysql_query('SELECT *,'tbl1' FROM (SELECT * FROM gslil0009) as table1
UNION SELECT *,'tbl2' FROM (SELECT * FROM gslil0028) as table2'
. ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['tbl1'];
}
I used the same solution as sel just add backslash to avoid error and added a name to the table names.
$result = mysql_query('SELECT *,\'table1\' AS tablename FROM (SELECT * FROM gslil0009) as table1
UNION SELECT *,\'table2\' AS tablename FROM (SELECT * FROM gslil0028) as table2'
. ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['tablename'];
}
i couldn't add comment on his post.

PHP MySQL Display counts

I have this query for counting the number of items in a category:
SELECT category, COUNT(*) AS category_count FROM users GROUP BY category
Which creates results looking like:
category category_count
========== ================
X 3
Y 2
Now, In PHP I want to display the counts of the categories. For example, I might want to echo the count from category X, how would I do it?
Thanks in advance
Assuming $result holds the result of your query:
while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'];
if ($row['category'] == 'X')
{
echo ' Count: ' . $row['category_count'];
}
echo '<br/>';
}
$res = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while($row = mysql_fetch_assoc($res)){
echo $row['category'].": ".$row['category_count']."<br/>";
}
$result = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
{
if ( $row['category'] == 'x' )
{
echo $row['category_count'];
}
}
while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'] . ' Count:' . $row['category_count'];
echo "<br>";
}
It would be better if you use the where clause in your query.
SELECT COUNT(*) AS category_count FROM users WHERE category = 'x'
$conn = mysql_connect("address","login","pas s");
mysql_select_db("database", $conn);
$Var = mysql_query("query");
While ($row = mysql_fetch_assoc($var) { echo $var["column"] }.

Categories