总结和显示总分

时间:2014-04-27 20:13:32

标签: php mysql sql

我有一个包含测验名称和分数

的表格

我一直在查看如何使用sql和php进行AVG(分数)。我无法弄明白。我要显示平均分数。所有数据都应显示在表格中。

Quiz     Score
Php       88
HTML      76
CCSS      78

Total     80

这是我的代码:

<?php
    $username = "root";
    $password = "";
    $hostname = "localhost";
    $database = "basketball_database";

    $con = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MYsql");
     //echo "Connected to mysql<br>";

     mysql_select_db("$database")
         or die("Could not select Basketball_database");
     //echo "Connected to database";

     echo "<div align=center>";

    //select from database
    $mysql = "SELECT quiz_name, AVG(score) FROM `thompkins@yahoo.com`";

    $mydata = mysql_query($mysql,$con);

    echo "<h2> Current Athletes </h2>";

    //create table
    echo "<table border=1
        <tr>
            <th>Quiz Name</th>
            <th>Score</th>
        </tr>";

    while($records = mysql_fetch_array($mydata)){
        echo "<tr>";
        echo "<td>".$records['quiz_name']."</td>";
        echo "<td>".$records['score']."</td>";
        echo "</tr>";
    } 


    // I want to display Total Score here
    echo "<tr>";
    echo "<td> Total Score: </td>";
    echo "<td>" . $records['score']. "</td>";
    echo "<tr>";

    echo "</div>";
    echo "</table>";
?>

2 个答案:

答案 0 :(得分:2)

您需要一个别名

AVG(score) as score 

然后在PHP中使用它

$records['score']

平均值通常适用于所有列数据或具有多个值的列。

这是demo

如果每列只有一个值,即一个测验名称和一个分数,则不需要在查询中使用AVG(),因为它将返回相同的值。

但是,如果您需要集体数据的平均值,您可以对所有数据使用avg(),如演示中所示,或者可以从PHP代码中执行。

答案 1 :(得分:0)

在这里 - 简单地总结一下。

//select from database
$mysql = "SELECT
               quiz_name
              ,AVG(score) as _avg
              ,SUM(score) as _sum
          FROM `thompkins@yahoo.com`
          GROUP BY quiz_name";
$mydata = mysql_query($mysql,$con);
echo "<h2>Current Athletes</h2>";

//create table
echo "<table border='1'>
    <tr>
        <th>Quiz Name</th>
        <th>Score</th>
    </tr>";

$total = 0;
while($records = mysql_fetch_array($mydata)){
    echo "<tr>
        <td>{$records['quiz_name']}</td>
        <td>{$records['_avg']}</td>
    </tr>";
    $total += $records['_sum'];
}
echo "<tr>
    <td>Total score:</td>
    <td>$total</td>
</tr>
</div></table>";