简体   繁体   中英

Summing and Displaying Total score

I have a table that has Quiz Name and Score

I've been looking up on how to AVG(Score) using sql and php. I can't figure it out. I what to display the average score. All the data should display in a table.

Quiz     Score
Php       88
HTML      76
CCSS      78

Total     80

Here is my code:

<?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>";
?>

You need an alias as

AVG(score) as score 

And then use it in PHP as

$records['score']

The average usually works on all column data or column having multiple values.

Here is a demo

If you have only one value per column ie one quiz name and one score then no need to use AVG() in the query since it will return the same value.

However if you need the average of collective data you can just use avg() on all data as shown in the demo or can do it from the PHP code.

Here it is - simply sum it up.

//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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM