views:

71

answers:

2
$result = mysql_query("SELECT avg(r.rate) FROM rate r where ImgName='1'");

this php is not working.

Originally my code is

<?php
$con = mysql_connect("localhost","root","sql");

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("photogallery", $con);

$result = mysql_query("SELECT avg(r.rate) FROM rate r ");
echo "<table border='0' cellspacing='5'>";
echo "<th> Average Rating </td>";

while($row = mysql_fetch_array($result))
{
    echo "<tr>";
    echo "<td> " . $row['rate'] . "</td>";
    echo "</tr>";
}

echo "</table>";

mysql_close($con);
?> 

the above is not showing any out put.

but modify code i.e. then its workin.

$result = mysql_query("SELECT r.rate FROM rate r ");

but i want to aggregate function

thanks in advance

+2  A: 

you can use an alias:

SELECT avg(r.rate) AS rate_average
  FROM rate r
 WHERE ImgName='1'

and then output:

echo "<td> " . $row['rate_average'] . "</td>";
knittl
thanks it's working
Vikram Phaneendra
Well... he does **not** has to use an alias. The value is available under `$row['avg(r.rate)']` but using alias is the only normal way to retrieve this value. I just though it's wrong to say "you have to" while you does not. ;)
Crozin
@cozin better? ;)
knittl
A: 

Your query is producing a scalar rather than a set of rows. If you want to get the average rate per item then you should do something like:

SELECT avg(r.rate) FROM rate r GROUP BY ItemIdColumn

And yes, if you want to fetch the value by column name, you should use an alias, like knittl mentioned.

alexb