Jump to content

[SOLVED] add mysql data


ngreenwood6

Recommended Posts

I have a question that will help me solve alot of my problems. I have a table in my database that stores numbers (ratings for pictures). I want to be able to get the average of these numbers. For example if there is 5 ratings in the database and the numbers are all 5 the average would be 5. I know that I can divide the numbers by mysql_num_rows but I do not know how to add the numbers in the database individually. I can display them on a page but am lost when it comes to adding them. Any help is appreciated.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/120084-solved-add-mysql-data/
Share on other sites

Well, perhaps I should add one line here

 

$result = mysql_query("SELECT rating FROM table WHERE pictureID = $pictureID");  //this is a query to get ratings for selected picture. the ine you use is probably different
$sum = 0;  // start with sum of ratings being 0
$count = 0;  //and count of ratings summed is also a 0
while ($row = mysql_fetch_array($result)) {   //go through all rows you got from mysql
$count++;   // increase $count by 1
$sum += $row['rating'];  //add rating in the current row to $sum
}
$average = $sum/$count;   //calculate average

 

Well post it out for me how you would do the whole query if you want to help me try to figure it out.

 

I had this

 


<?php
$host = "host";
$user = "user";
$pass = "pass";
$db = "db";
$table = "table";

$connect = mysql_connect($host, $user, $pass);

mysql_select_db($db);

$select = "SELECT AVG(rating) from $table"; //rating is my field

$result = mysql_query($select);

echo $result;

?>

 

Any suggestions

$select = "SELECT AVG(rating) AS average from $table"; //note: 'AS average' is mySQL alias, it will be the key in $row array
$result = mysql_query($select);

$row = mysql_fetch_array($result);  //$result is a resource, from witch you have to fetch rows (even if there's only one row)

echo $row['average'];

 

Edit:

Download mySQL GUI Tools. There's a nice tool there: mySQL Query Browser, that'll let you test queries without having to write php code.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.