All i am doing is saving user ratings and reviews to table and then calling it from database. Now what I want to do is add all the ratings (like: 5+4+3= 12) and then divide them by count of the ratings (12/3 = 4) and get average rating or aggregate rating.
I am able to display the reviews but how can I add all values from rating column and get average value.
if (mysqli_num_rows($mesult) > 0) {
$count = mysqli_num_rows($mesult);
echo '<p class="">'.$count.' Reviews</p>';
while($row = mysqli_fetch_assoc($mesult)) {
$name =$row["name"];
$text =$row["text"];
$heading =$row["heading"];
$rating =$row["rating"];
echo '<div class="review" itemscope itemtype="http://schema.org/Review"> <meta itemprop="itemReviewed" content ="'.$title.'"/> <p class="heading"><strong>'.$heading.'</strong></p><div class="ratings" itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"> <meta itemprop="worstRating" content = "1"/><span itemprop="ratingValue">'.$rating.'</span>/<span itemprop="bestRating">5</span></div><p class="reviewtext" itemprop="description">'.$text.'</p><div class="reviewby" itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">'.$name.'</span></div></div>';
}
Also what I am querying is
$loutput ="SELECT * FROM rating
WHERE product=$ID";
$mesult = mysqli_query($conns,$loutput);
You can also use MySQL's AVG() to calculate the average rating:
SELECT AVG(rating) AS avgRating FROM myTable;
This is how you round the result to X decimals:
SELECT ROUND(AVG(rating), X) AS avgRating FROM myTable;
$loutput ="SELECT AVG(Column_name) as avg FROM rating WHERE product='".$ID."'";
$mresult=mysqli_fetch_assoc(mysqli_query($loutput));
echo $mresult['avg'];
Use aggregate function
to get the average use the avg()
SELECT avg(rating) from rating;
Related
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];
I could not get rid of a problem and want your help.
This is what I want to do briefly;
There are job postings in Table A, and these job posts have ratings in table B. When I list the job postings, I want to list the job postings by the highest percentage percentage.
$query = $db->query("SELECT job_listing.id,
FROM job_listing
LEFT JOIN job_order_ratings ON job_order_ratings.job_id = job_listing.id
WHERE job_listing.job_status = 2
ORDER BY *** ASC")->fetchAll(PDO::FETCH_ASSOC);
score table
I normally calculate the score rating of a job this way. I want to list the points according to the total rate while listing
public function rateTotal($rate1, $rate2, $rate3, $count= '')
{
$rate_total = $rate1 + $rate2 + $rate3;
$total = $rate_total / $count;
return number_format(round(($total / 3), 1), 1, '.', '');
}
Since there are three ratings, I divide it into the last three
When I list job postings in sql query, I want it to list by percentage. It has to calculate just like I did in the rateTotal function.
I'm sorry for my bad english
$sql = "SELECT
job_listing.id,
FORMAT((SUM(column1 + column2 + column3)/ COUNT(column)) / 3, 2) AS 'rating
FROM job_listing
LEFT JOIN job_order_ratings ON job_order_ratings.job_id =
job_listing.id
WHERE job_listing.job_status = 2 ORDER BY job_order_ratings.field DESC"
Did you try this way?
When u use ASC (ascending), you will order numbers from smaller to bigger, if you use DESC (descending) is from bigger to smaller number 10,9,8,7,6,5...
i have this code that makes a sum of 2 tables
<div align="right"> Total Vanzari ziua curenta: <i><strong>
<?php
$query = "SELECT (SELECT SUM(totaldeplata) FROM vanzari WHERE
datainregistrarii >= CURRENT_DATE()) + (SELECT SUM(totaldeplata) FROM
players WHERE datainregistrarii >= CURRENT_DATE()) as result";
$query_run = mysql_query($query);
$row = mysql_fetch_assoc($query_run);
$sum = $row['result'];
echo "sum of two different column from two tables : "+ $sum;
?></strong> </i> Lei
</div>
it display a sum of 2 row from 2 different tables
is there a way to store this maximul value into database (its actually the daily sale so the maximum value need to be stored into a table row)
i have a database with 2 different tables
One table (players) contain a column nammed "totaldeplata" that contains numbers (price)
Other table (vanzari) contain a column like the first one nammed "totaldeplata" it hase the same value inside numbers (the price)
i manage to display the sum of all column for each table like this:
<div align="right"> Total Comenzi luna curenta: <i><strong>
<?php
$query = "SELECT * FROM vanzari WHERE MONTH(datainregistrarii) =
MONTH(CURRENT_DATE())";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['totaldeplata'];
}
echo $qty;
?></strong> </i> Lei
</div>
But this, display only the sum of one table, so i have to write the same code to display the sum of other column in the secound table (in this case the players table)
I need to sum all the numbers from columns "totaldeplata" from tables: vanzari and players, and display them as one number (to sum all the numbers and display them)
Actualy Sum numbers from columns "totaldeplata" from both tables "vanzari" and "players" and display them.
Any ideea how to do that? :)
SELECT (SELECT SUM(field1) FROM table1) + (SELECT SUM(field2) FROM table2) as result
According to your above code and table name.
<?php
$query = "SELECT (SELECT SUM(totaldeplata) FROM vanzari) + (SELECT SUM(totaldeplata) FROM players) as result";
$query_run = mysql_query($query);
$row = mysql_fetch_assoc($query_run);
$sum = $row['result'];
echo "sum of two different column from two tables : "+ $sum;
?>
I'm trying to display and sort an array by an average created using data from a database. I'm retrieving three variables from the database and creating an average from these values. This value is then placed inside a new array to be sorted along with the rest of the database data.
Am I right in thinking that having the SQL query inside the loop isn't a great idea? (Performance issue?)
Is there any alternative that's available? I've attached the code below:
^ database connection/query string to retrieve all data...
$result = $stmt_business_list->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach($result as $row){
$single_business_id = $row['id'];
$name = $row['name'];
//Query to get ALL the service, value and quality ratings for certain business
$test_query = "SELECT * FROM rating WHERE business_id = $single_business_id";
$test_query_stmt = $dbh->prepare($test_query);
$test_query_stmt->execute();
$test_row = $test_query_stmt->fetchAll(PDO::FETCH_ASSOC);
$total_value = $total_quality = $total_service = 0;
foreach($test_row as $review)
{
$total_value += $review['value'];
$total_quality += $review['quality'];
$total_service += $review['service'];
}
$bayesian_value = (($set_site_average_review_count * $set_site_average_review_score) + $total_value) / ($set_site_average_review_count + $business_review_count);
$bayesian_quality = (($set_site_average_review_count * $set_site_average_review_score) + $total_quality) / ($set_site_average_review_count + $business_review_count);
$bayesian_service = (($set_site_average_review_count * $set_site_average_review_score) + $total_service) / ($set_site_average_review_count + $business_review_count);
$average_bayesian_rating = ($bayesian_value + $bayesian_quality + $bayesian_service) / 3;
$average_bayesian_rating = $average_bayesian_rating;
array_push($items, array(
"id"=>"$single_business_id",
"name"=>"$name",
"value"=>"$total_value",
"quality"=>"$total_quality",
"service"=>"$total_service",
"average"=>"$average_bayesian_rating"));
echo
'Name: '.$name.'<br>
Value: '.$total_value.'<br>
Quality: '.$total_quality.'<br>
Service: '.$total_service.'<br>
Average: '.$average_bayesian_rating.'<br><br>';
}
}
The page will be split up by a separate pagination script and will only display 6 objects at a time, but over time this may change so I do have an eye on performance as much as I can.
SQL aggregate queries are made for this kind of thing.
Use this query to summarize the results
SELECT b.name, b.id,
SUM(value) total_value,
SUM(quality) total_quality,
SUM(service) total_service,
COUNT(*) review_count,
avg_reviews_per_biz
FROM business b
JOIN ratings r ON b.id = r.business_id
JOIN (
SELECT COUNT(DISTINCT business_id) / COUNT(*) avg_reviews_per_biz
FROM ratings
) a ON 1=1
GROUP BY b.name, b.id, avg_review_per_biz
This will give you one row per business showing the summed ratings and the number of ratings. This result set will have the following columns
name business name
id business id
total_value sum of value ratings for that business
total_quality sum of quality ditto
total_service sum of service ditto
review_count number of reviews for business "id"
avg_reviews_per_biz avg number of reviews per business
The last column has the same value for all rows of your query.
You can then loop over these row one business at a time doing your statistical computations.
I can't tell from your question where you're getting variables like $set_site_average_review_count, so I can't help with those computations.
You'll find that SQL aggregate querying is very powerful indeed.