我有一个简单的mysql表,其中包含' ratee'作为用户和评级是给予该用户的评级。我想显示该用户被评级的次数以及这些评级的平均值。前者如下面的代码所示,但后者没有。我哪里出错了?我正在使用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;
答案 0 :(得分:1)
mysqli_query()
返回一个Mysql结果对象。因此,你不能只是回应它。您仍需要mysqli_fetch_row()
或类似内容。
答案 1 :(得分:1)
你的问题是你甚至懒得去完成一个基本的mysqli教程或阅读mysqli文档。
mysqli_avg()
这样的功能。周期。mysqli_query()
返回mysqli_result object,而不是平均值。您可以使用mysqli_result object的fetch _ *()方法之一来获取MySQL计算的实际平均值:请参阅以下代码:
$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];
答案 2 :(得分:0)
试试这个
$sql = "SELECT * FROM ratings WHERE ratee='" . $user1 . "'";
$result = mysqli_query($conn, $sql);
$rating = mysqli_fetch_array($result,MYSQLI_ASSOC);
现在$ rating是一个数组,你可以打印你的表格数据
使用:echo $rating['ratee'];
或echo $rating['rating'];
平均试试这个:
$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'];
答案 3 :(得分:0)
对你来说也许为时已晚,但也许其他人会受益:
从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;
}