I have a simple mysql table with 'ratee' being the user and rating being the rating given to that user. I want to display how many times that user has been rated and what the average of those ratings are. The former works as shown in the code below but the latter does not. Where am i going wrong please? I am using PHP.
//working
$sql = "SELECT * FROM ratings WHERE ratee='" . $user1 . "'";
$result = mysqli_query($conn, $sql);
$ratingsqty = mysqli_num_rows($result);
echo $ratingsqty;
//not working 1
$sql = "SELECT * FROM ratings WHERE ratee='" . $user1 . "'";
$result = mysqli_query($conn, $sql);
$rating = mysqli_avg($result);
echo $rating;
//not working 2
$sql = "SELECT avg(rating) FROM ratings WHERE ratee='" . $user1 . "'";
$rating = mysqli_query($conn, $sql);
echo $rating;
mysqli_query()
returns a Mysql results object. As such, you can't just echo it. You'll still need mysqli_fetch_row()
or similar.
Try this
$sql = "SELECT * FROM ratings WHERE ratee='" . $user1 . "'";
$result = mysqli_query($conn, $sql);
$rating = mysqli_fetch_array($result,MYSQLI_ASSOC);
now $rating is an array by this you can print data of your table
using: echo $rating['ratee'];
or echo $rating['rating'];
For average try this:
$sql = "SELECT avg(rating) as av FROM ratings WHERE ratee='" . $user1 . "'";
$result = mysqli_query($conn, $sql);
$rating = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo $rating['av'];
Your problem is that you do not even bother to go through a basic mysqli tutorial or read mysqli documentation.
mysqli_avg()
. Period.mysqli_query()
returns a mysqli_result object, not the average. You can use one of the fetch_*() methods of mysqli_result object to get the actual average calculated by MySQL:See the code below:
$sql = "SELECT avg(rating) FROM ratings WHERE ratee='" . $user1 . "'"; //in real life code pls take some measures to prevent sql injection attacks
$result = mysqli_query($conn, $sql); //in real life code pls check for execution errors
$rating = $result->fetch_array(MYSQLI_NUM)
echo $rating[0];
Perhaps too late for you but maybe others will benefit:
Get one line result from MySQL:
$val = fetch_one_record("SELECT some_field FROM some_table LIMIT 1);
function fetch_one_record($sql) {
$conn = db_connect();
$result = array_shift($conn->query($sql)->fetch_assoc());
$conn->close();
return $result;
}